BackmediumStringsSalesforceInfosys

Reverse Character Groups Solution

Problem Statement

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.

Example 1
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'.

Example 2
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.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Reverse Character Groups — Problem Statement & Solution Guide

StringsMediumSTRREV 1001
TimeO(n)
|
SpaceO(n)

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

Example 1

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'.

Example 2

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

JavaScript Solution
Time: O(n)
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

SalesforceInfosys

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.