easyStringsPattern: Slow/Fast Pointers

Shift Hash Characters Solution

Problem Statement

You are given a string s. Rearrange the characters of s such that all hash characters ('#') are moved to the end of the string, while the relative order of all other characters remains unchanged. Return the modified string.

Examples

Example 1:
Input:s = "a#b#c"
Output:"abc##"
Explanation: The non-hash characters 'a', 'b', and 'c' maintain their relative order, while the two '#' characters are shifted to the end.
Example 2:
Input:s = "###code"
Output:"code###"
Explanation: All three '#' characters at the beginning are shifted to the end of the string, keeping 'code' intact at the front.

Constraints

  • 1 <= s.length <= 10^5
  • s consists only of lowercase English letters and '#' characters.
Time: O(N) Space: O(N)
Convert the string to a mutable array and use a two-pointer read/write approach. The write pointer tracks the placement of non-hash characters, which are copied forward sequentially, and the rest of the array is backfilled with hashes in a single pass.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.