Package Label Generator — Problem Statement & Solution Guide
Problem Description
Given a string representing a package label, transform it according to the following rule: if the label length is divisible by three, divide the label into consecutive blocks of three characters and reverse the characters inside each block, then concatenate the blocks in their original order. If the length is not divisible by three, reverse the entire label. The function should return the resulting string.
DSA Pattern Breakdown
DSA Pattern Breakdown
"Package Label Generator"
WHY DOES IT MATTER?
The pattern exemplifies block‑wise processing, a common technique in streaming, cryptography, and data‑compression where fixed‑size chunks are transformed independently, allowing parallelism and predictable memory usage.
OPTIMIZATION CHALLENGE
Realizing that each character is touched at most twice—once for block reversal or full reversal—eliminates the need for costly string concatenations and reduces the algorithm to linear time.
REAL-WORLD CONNECTION
Think of a conveyor belt that groups parcels in threes; each group is inspected and its orientation flipped before the belt continues, mirroring how network packets are often processed in fixed‑size frames.
When coding, convert the immutable string to a mutable array once, then run a single loop stepping by three; this avoids hidden O(n) costs of repeated slicing.
COMPLEXITY AT A GLANCE
O(n)O(1)Core Theory — Why This Approach?
The transformation rule hinges on recognizing a periodic structure in the input string: when its length is a multiple of three, the string can be partitioned into fixed-size blocks that can be processed independently. This property enables a linear‑time algorithm because each character belongs to exactly one block and is visited a constant number of times. A naive solution might first check divisibility, then repeatedly slice the string using high‑level substring operations that allocate new memory for each block, leading to O(n²) time on large inputs due to repeated copying. The optimal paradigm treats the string as an array of characters and performs in‑place reversal of each three‑character segment, or a single full‑string reversal when the length condition fails, guaranteeing O(n) time and O(1) auxiliary space.
Interview Questions on This Problem
Q1How would you handle the case where the label length is not divisible by three?
Simply reverse the entire string using a two‑pointer swap; this covers the fallback case in O(n) time.
Q2Can you solve the problem without using extra string buffers?
Yes—by converting the string to a mutable character array (or using a StringBuilder) and performing in‑place swaps for each three‑character block or the whole array.
Q3What is the time complexity if you used substring concatenation inside a loop for each block?
Each substring creates a new string, so the total work becomes O(n²) in the worst case, which is unacceptable for large inputs.
Examples
Input
ABCDEF
Output
CBAFED
Explanation: Length 6 is a multiple of 3. Blocks: ["ABC","DEF"]. Reverse each block → "CBA" and "FED". Concatenate → "CBAFED".
Input
A1B2C
Output
C2B1A
Explanation: Length 5 is not a multiple of 3, so reverse the whole string: "C2B1A".
Input
XYZ
Output
ZYX
Explanation: Length 3 is a multiple of 3. Single block "XYZ" reversed → "ZYX".
Input
HELLOWORLD
Output
DLROWOLLEH
Explanation: Length 10 is not a multiple of 3, reverse the entire label → "DLROWOLLEH".
Constraints
- 1 <= label.length <= 100000
- label consists of printable ASCII characters (letters, digits, symbols)
- The transformation must run in O(n) time and O(1) additional space besides the output
Optimal Approach & Strategy
Convert the input to a char array, then either reverse each three‑character segment in place or reverse the entire array with two pointers, achieving O(n) time and O(1) extra space.
Brute Force Approach
Create a new string for each three‑character block using substring and reverse it, concatenating results, or reverse the whole string when needed, leading to repeated allocations.
Verified Code Solutions
function transformLabel(label) {
const n = label.length;
if (n === 0) return "";
if (n % 3 !== 0) {
return label.split('').reverse().join('');
}
let res = '';
for (let i = 0; i < n; i += 3) {
res += label[i + 2] + label[i + 1] + label[i];
}
return res;
}
const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim();
if (input.length > 0) {
console.log(transformLabel(input));
}#include <bits/stdc++.h>
using namespace std;
string transformLabel(const string& label) {
size_t n = label.size();
if (n == 0) return "";
if (n % 3 != 0) {
string rev = label;
reverse(rev.begin(), rev.end());
return rev;
}
string res;
res.reserve(n);
for (size_t i = 0; i < n; i += 3) {
res.push_back(label[i + 2]);
res.push_back(label[i + 1]);
res.push_back(label[i]);
}
return res;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s;
if (cin >> s) {
cout << transformLabel(s);
}
return 0;
}import java.io.*;
public class Main {
static String transformLabel(String label) {
int n = label.length();
if (n == 0) return "";
if (n % 3 != 0) {
return new StringBuilder(label).reverse().toString();
}
StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; i += 3) {
sb.append(label.charAt(i + 2));
sb.append(label.charAt(i + 1));
sb.append(label.charAt(i));
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
if (s != null) {
System.out.print(transformLabel(s));
}
}
}import sys
def transform_label(label: str) -> str:
n = len(label)
if n == 0:
return ""
if n % 3 != 0:
return label[::-1]
# n divisible by 3
parts = []
for i in range(0, n, 3):
block = label[i:i+3]
parts.append(block[::-1])
return "".join(parts)
if __name__ == "__main__":
data = sys.stdin.read().strip()
if data:
print(transform_label(data))function transformLabel(label) {
const n = label.length;
if (n === 0) return "";
if (n % 3 !== 0) {
return label.split('').reverse().join('');
}
let res = '';
for (let i = 0; i < n; i += 3) {
res += label[i + 2] + label[i + 1] + label[i];
}
return res;
}
const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim();
if (input.length > 0) {
console.log(transformLabel(input));
}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.