πΉ Problem: 386 Lexicographical Numbers
Difficulty: #Medium
Tags: #Lexicographical #DFS
π Problem Summary
Return a lexicographically sorted list of all integers from
1tonin their string representation.
π§ My Thought Process
Brute Force Idea:
This problem is kinda a brute force problem. You can just generate all numbers from1ton, convert them to strings, and sort them. But that would be inefficient or you can think for iterating over the numbers and generating them in lexicographical order.-
Optimized Strategy:
I used the later bruteforce approach. Than I saw it's a iterative DFS solution (instead of recursion, I used a stack).- Start iterating from
1and append the current number to the result. - Now, check if the current number multiplied by
10is less than or equal ton. If it is, set current number tocurrent * 10. - If not, check if the current number plus
1is less than or equal ton. If it is, increment the current number by1. - But there is a twist, if the current number plus
1results in a number that has has a mode of10we can have same number again, so we need to backtrack before incrementing the current number. - So, check if the current number is divisible by
10and if the mode is9. We will divide the current number by10to backtrack.
- Start iterating from
Algorithm Used:
[[iterative_dfs]]
βοΈ Code Implementation (Python)
class Solution:
def lexicalOrder(self, n: int) -> List[int]:
res = []
curr = 1
for i in range(n):
res.append(curr)
if curr*10 <= n:
curr = curr*10
else:
while curr%10 == 9 or curr >= n:
curr = curr//10
curr += 1
return res
β±οΈ Time & Space Complexity
-
Time: O(n)
- We iterate through numbers from
1ton, and each number is processed in constant time.
- We iterate through numbers from
-
Space: O(n)
- The result list stores all numbers from
1ton.
- The result list stores all numbers from
π§© Key Takeaways
- β
What concept or trick did I learn?
- I learned how to generate numbers in lexicographical order using an iterative DFS approach.
- π‘ What made this problem tricky?
- The tricky part was figuring out the backtracking condition when the current number reaches a point where it can no longer be multiplied by
10.
- The tricky part was figuring out the backtracking condition when the current number reaches a point where it can no longer be multiplied by
- π How will I recognize a similar problem in the future?
- If I encounter a problem that requires generating numbers in a specific order, especially lexicographically, I can apply this iterative DFS approach.
π Reflection (Self-Check)
- [β ] Could I solve this without help?
- [β ] Did I write code from scratch?
- [β ] Did I understand why it works?
- [β ] Will I be able to recall this in a week?
π Progress Tracker
| Metric | Value |
|---|---|
| Day | 13 |
| Total Problems Solved | 347 |
| Confidence Today | π |
Top comments (0)