Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1625: Lexicographically Smallest String After Applying Operations

In this guide, we solve Leetcode #1625 Lexicographically Smallest String After Applying Operations in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given a string s of even length consisting of digits from 0 to 9, and two integers a and b. You can apply either of the following two operations any number of times and in any order on s: Add a to all odd indices of s (0-indexed).

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Depth-First Search, Breadth-First Search, String, Enumeration

Intuition

We need to explore a structure deeply before backing up, which suits DFS.

DFS keeps local context on the call stack and is easy to implement recursively.

Approach

Define a recursive DFS that carries the necessary state.

Combine child results as the recursion unwinds.

Steps:

  • Define a recursive DFS with state.
  • Visit children and combine results.
  • Return the final aggregation.

Example

Input: s = "5525", a = 9, b = 2 Output: "2050" Explanation: We can apply the following operations: Start: "5525" Rotate: "2555" Add: "2454" Add: "2353" Rotate: "5323" Add: "5222" Add: "5121" Rotate: "2151" Add: "2050"​​​​​ There is no way to obtain a string that is lexicographically smaller than "2050".

Python Solution

class Solution: def findLexSmallestString(self, s: str, a: int, b: int) -> str: q = deque([s]) vis = {s} ans = s while q: s = q.popleft() if ans > s: ans = s t1 = ''.join( [str((int(c) + a) % 10) if i & 1 else c for i, c in enumerate(s)] ) t2 = s[-b:] + s[:-b] for t in (t1, t2): if t not in vis: vis.add(t) q.append(t) return ans

Complexity

The time complexity is O(n2×102)O(n^2 \times 10^2)O(n2×102) and the space complexity is O(n)O(n)O(n), where nnn is the length of string sss. The space complexity is O(n)O(n)O(n), where nnn is the length of string sss.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy