Reverse Character Groups — Problem Statement & Solution Guide
Problem Description
Given a string of digits and letters, reverse each group of 3 characters. If the string length is not a multiple of 3, reverse the entire string.
Examples
Input
abcdef
Output
cbafed
Explanation: Step-by-step: 1. Divide the input string 'abcdef' into groups ['abc', 'def']. 2. Reverse each group to ['cba', 'fed']. 3. Join the reversed groups to get the output 'cbafed'.
Input
abcd
Output
dcba
Explanation: Step-by-step: 1. The string 'abcd' is not a multiple of 3. 2. Reverse the entire string to get the output 'dcba'.
Constraints
- Input string should be a unique alphanumeric identifier.
- The length of the input string should be between 1 and 100.
Optimal Approach & Strategy
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.
Brute Force Approach
A brute-force approach would involve reversing the entire string first, then iterating over the string in chunks of 3 characters, reversing each chunk separately. However, this approach would have a time complexity of O(n^2) due to the extra reverse operation.
Verified Code Solutions
function reverseCharacterGroups(str) { let result = ''; if (str.length < 3) { return str.split('').reverse().join(''); } for (let i = 0; i < str.length; i += 3) { let group = str.substring(i, Math.min(i + 3, str.length)); result += group.split('').reverse().join(''); } return result; }class Solution {
public String reverseCharacterGroups(String s) {
if (s.length() % 3 == 0) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i += 3) {
sb.append(new StringBuilder(s.substring(i, i + 3)).reverse().toString());
}
return sb.toString();
} else {
return new StringBuilder(s).reverse().toString();
}
}
}def reverse_character_groups(s: str) -> str:
if len(s) % 3 == 0:
return ''.join(''.join(reversed(s[i:i+3])) for i in range(0, len(s), 3))
else:
return s[::-1]function reverseCharacterGroups(str) { let result = ''; if (str.length < 3) { return str.split('').reverse().join(''); } for (let i = 0; i < str.length; i += 3) { let group = str.substring(i, Math.min(i + 3, str.length)); result += group.split('').reverse().join(''); } return result; }Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.