Overflow in intermediate arithmetic
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string.
Return the lexicographically smallest string you could have after applying the mentioned step any number of moves.
Example 1:
Input: s = "cba", k = 1 Output: "acb" Explanation: In the first move, we move the 1st character 'c' to the end, obtaining the string "bac". In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb".
Example 2:
Input: s = "baaca", k = 3 Output: "aaabc" Explanation: In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab". In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc".
Constraints:
1 <= k <= s.length <= 1000s consist of lowercase English letters.Problem summary: You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string. Return the lexicographically smallest string you could have after applying the mentioned step any number of moves.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math
"cba" 1
"baaca" 3
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #899: Orderly Queue
class Solution {
public String orderlyQueue(String s, int k) {
if (k == 1) {
String ans = s;
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < s.length() - 1; ++i) {
sb.append(sb.charAt(0)).deleteCharAt(0);
if (sb.toString().compareTo(ans) < 0) {
ans = sb.toString();
}
}
return ans;
}
char[] cs = s.toCharArray();
Arrays.sort(cs);
return String.valueOf(cs);
}
}
// Accepted solution for LeetCode #899: Orderly Queue
func orderlyQueue(s string, k int) string {
if k == 1 {
ans := s
for i := 0; i < len(s)-1; i++ {
s = s[1:] + s[:1]
if s < ans {
ans = s
}
}
return ans
}
t := []byte(s)
sort.Slice(t, func(i, j int) bool { return t[i] < t[j] })
return string(t)
}
# Accepted solution for LeetCode #899: Orderly Queue
class Solution:
def orderlyQueue(self, s: str, k: int) -> str:
if k == 1:
ans = s
for _ in range(len(s) - 1):
s = s[1:] + s[0]
ans = min(ans, s)
return ans
return "".join(sorted(s))
// Accepted solution for LeetCode #899: Orderly Queue
struct Solution;
impl Solution {
fn orderly_queue(s: String, k: i32) -> String {
let mut s: Vec<char> = s.chars().collect();
let n = s.len();
if k > 1 {
s.sort_unstable();
s.into_iter().collect()
} else {
let mut res = s.to_vec();
for i in 0..n {
let mut t = vec![];
for j in i..n {
t.push(s[j]);
}
for j in 0..i {
t.push(s[j]);
}
if t < res {
res = t;
}
}
res.into_iter().collect()
}
}
}
#[test]
fn test() {
let s = "cba".to_string();
let k = 1;
let res = "acb".to_string();
assert_eq!(Solution::orderly_queue(s, k), res);
let s = "baaca".to_string();
let k = 3;
let res = "aaabc".to_string();
assert_eq!(Solution::orderly_queue(s, k), res);
}
// Accepted solution for LeetCode #899: Orderly Queue
function orderlyQueue(s: string, k: number): string {
if (k > 1) {
return [...s].sort().join('');
}
const n = s.length;
let min = s;
for (let i = 1; i < n; i++) {
const t = s.slice(i) + s.slice(0, i);
if (t < min) {
min = t;
}
}
return min;
}
Use this to step through a reusable interview workflow for this problem.
Simulate the process step by step — multiply n times, check each number up to n, or iterate through all possibilities. Each step is O(1), but doing it n times gives O(n). No extra space needed since we just track running state.
Math problems often have a closed-form or O(log n) solution hidden behind an O(n) simulation. Modular arithmetic, fast exponentiation (repeated squaring), GCD (Euclidean algorithm), and number theory properties can dramatically reduce complexity.
Review these before coding to avoid predictable interview regressions.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.