File: increasing-decreasing-string/solution.py

Date: 2026-06-06

Time: 17:03

Purpose

This file solves LeetCode 1370: Increasing Decreasing String. It implements the "sort string" algorithm that repeatedly sweeps through available characters in ascending then descending order, appending one of each to the result until all characters are consumed. The file is self-contained: solution class + unit tests in one module.

Key Components

Solution.sortString(s: str) -> str

The core algorithm. Takes a string of lowercase English letters and returns a reordered string built by alternating forward (a→z) and backward (z→a) sweeps through the character set.

Contract: Input must be lowercase English letters only. Output is a permutation of the input with the same character frequencies.

TestSortString

Nine test cases covering: LeetCode examples, single character, uniform characters, pre-sorted/reverse-sorted inputs, and a full-alphabet input.

Patterns

Counting sort via fixed-size array: Rather than using collections.Counter or sorting the string, the solution uses a 26-element integer array (count) indexed by character ordinal offset. This is the canonical approach when the alphabet is small and known — O(1) space (fixed 26), avoids hash overhead.

Drain loop with remaining counter: The remaining variable tracks total characters left. The outer while remaining > 0 loop runs until all characters are consumed. Each inner loop (forward sweep, backward sweep) decrements both the per-character count and the global remaining counter, so the loop terminates in at most ceil(len(s) / numdistinctchars) iterations of the outer loop.

Append-to-list then join: Standard Python idiom for string building — result is a list, joined at the end. Avoids O(n²) string concatenation.

Dependencies

Imports: Only unittest from the standard library. No external dependencies.

Imported by: The "Imported By" list in the prompt is misleading — those are test files from *other* problems that import unittest, not files that import this module. This solution is standalone.

Flow

1. Build a frequency array count[0..25] by scanning input string once — O(n).

2. Enter drain loop:

3. Repeat until remaining == 0.

4. Join the result list into a string and return.

Each full iteration of the outer loop appends at most one instance of each distinct character (once forward, once backward). For input "aaaabbbbcccc", the first iteration appends a,b,c (forward) then c,b,a (backward) = "abccba", then repeats for the second batch.

Invariants

Error Handling

None. The function assumes valid input (lowercase English letters). No bounds checking, no type validation. Invalid input (uppercase, non-alpha, empty string) would silently produce incorrect results or an empty string — but LeetCode constraints guarantee valid input.

Topics to Explore

Beliefs