Separate the alphabet and digit such that their relative order remains the same in On time and O1 space
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
In computer science, efficiently separating alphabets and digits from a character array while maintaining their relative order is an interesting problem that can have multiple applications, such as input validation or data cleanup. The challenge lies in achieving this with an algorithm that operates in O(n) time complexity and O(1) space complexity. In this article, we will explore how to solve this problem and understand the technicalities involved.
Problem Statement
Given a string that contains a mix of letters and digits, separate the letters and digits such that all letters appear before all digits, while maintaining their initial order. We need to achieve this with one scan of the string and constant space.
Approach
To solve this problem in O(n) time and O(1) space, we use the two-pointer technique with an in-place modification of the input array. This approach ensures that we neither use additional space beyond a few variables nor exceed a single traversal of the string.
Steps
- Initialize two pointers:
write_pointerat index 0.current_pointerat index 0.
- Iterate through the string using
current_pointer. - If the character at
current_pointeris an alphabet, swap it with the character atwrite_pointer. - Increment both pointers if a swap occurs (indicating that the next available write position has moved).
- If the character is a digit, simply increment
current_pointer. - After the loop,
write_pointerwill point to the start of the digits section. - At this point, the array is rearranged with alphabets followed by digits while maintaining the original order.
Example
Consider the string: "a1b2c3"
- Initial configuration:
a1b2c3 - After first pass:
a1b2c3(swap 'a' with 'a') - After second pass:
ab1c23(swap 'b' with '1') - After third pass:
abc123(swap 'c' with '1')
The resulting string is "abc123", where the letters "abc" are followed by the digits "123", with their relative order preserved.
Pseudocode
Here is the pseudocode detailing the approach:
This algorithm ensures that each element is processed exactly once, resulting in O(n) time complexity.
Key Considerations
- Space Complexity: The method uses
O(1)space as it only operates with a fixed number of extra variables (write_pointer,current_pointer). - Preservation of Order: Both the initial order of the alphabets and the digits are preserved.
- Boundary Cases: Handling edge cases such as an entirely alphabetic or digit string requires no special logic since the algorithm naturally accommodates these scenarios.
Summary Table
| Key Aspect | Explanation |
| Time Complexity | O(n) |
| Space Complexity | O(1) |
| Strategy Used | Two-pointer technique (in-place modification) |
| Order Preservation | Both alphabets and digit orders are maintained |
| Applicability | Strings containing mixed alphabets and digits |
Additional Considerations
Edge Cases
- Empty String: The function should return an empty result without error.
- Single Character: Depending on whether it's an alphabet or digit, it remains unchanged.
Error Handling
The algorithm assumes input validation occurs outside its scope. Thus, non-alphanumeric characters are not processed, as this would require additional checks.
By understanding and leveraging efficient problem-solving techniques like the two-pointer method, we can effectively separate alphabets and digits in a string within the constraints of O(n) time and O(1) space. This approach is simple yet powerful for applications involving structured data processing within systems constrained by memory and performance limitations.
Related reading
- Set Cover or Hitting Set; Numpy, Least element combinations to make up full set
- Set every cell in matrix to 0 if that row or column contains a 0
- Set time and speed complexity
- SGDStochastic Gradient Descent vs Backpropagation
- Separating celery consumer and producer
- Serialize Class containing Dictionary member
- Set database timeout in Entity Framework
- setNeedsLayout vs. setNeedsUpdateConstraints and layoutIfNeeded vs updateConstraintsIfNeeded

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.