mediumStringsPattern: STRREV 1001
Reverse Character Groups Solution
Problem Statement
Given a string of digits and letters, reverse each group of 3 characters. If a group has less than 3 characters, reverse the entire string.
Examples
Example 1:
Input:abcdef
Output:cbafed
Explanation: Reversing each group of 3 characters: 'abc' becomes 'cba' and 'def' becomes 'fed', resulting in 'cbafed'
Example 2:
Input:abcdefghi
Output:cbadefihg
Explanation: Reversing each group of 3 characters: 'abc' becomes 'cba', 'def' becomes 'fed', and 'ghi' becomes 'ihg', resulting in 'cbadefihg'
Example 3:
Input:ab
Output:ba
Explanation: Since the label length is less than 3, the entire label is reversed, resulting in 'ba'
Constraints
- Input string should be a unique alphanumeric identifier.
- The length of the input string should be between 1 and 100.
Time: O(n) Space: O(n)
The optimal approach is to iterate over the string only once, and in each iteration, reverse the current 3-character group and add it to the result. This approach has a time complexity of O(n) since we only need to iterate over the string once.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
No solution code is currently loaded.
Complete this code in the workspace editor.
