Skip to content

Commit 2596575

Browse files
committed
Add 1625
1 parent 5cc1929 commit 2596575

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

Readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,7 @@ https://leetcode.com/jummyegg/
395395
| 1615 | Maximal Network Rank | Medium | O(N) | O(1) | Graph | | |
396396
| 1618 | Maximum Font to Fit a Sentence in a Screen | Medium | O(logN) | O(1) | Premium, String, Binary Search | | 🔒 |
397397
| 1624 | Largest Substring Between Two Equal Characters | Easy | O(N) | O(1) | String | | |
398+
| 1625 | Lexicographically Smallest String After Applying Operations | Medium | O(N*N) | O(N) | BFS, DFS | | |
398399
| 1629 | Slowest Key | Easy | O(N) | O(1) | String | | |
399400
| 1631 | Path With Minimum Effort | Medium | O(N\*M\*logH) | O(M\*N) | Binary Search, DFS, BFS, Union Find, Graph | | |
400401
| 1634 | Add Two Polynomials Represented as Linked Lists | Medium | O(N) | O(1) | Premium, Linked List | | 🔒 |
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#
2+
# @lc app=leetcode id=1625 lang=python3
3+
#
4+
# [1625] Lexicographically Smallest String After Applying Operations
5+
#
6+
7+
# @lc code=start
8+
# TAGS: BFS, DFS
9+
10+
11+
class Solution:
12+
"""
13+
We Can bruteforce this problem because we notice that 10a = 0a
14+
"""
15+
# 136 ms, 92.93%. Time: O(N^2). Space: O(N)
16+
17+
def findLexSmallestString(self, s: str, a: int, b: int) -> str:
18+
# Try all shifting positions and compare
19+
def get_smaller(ans, s):
20+
for _ in range(len(s)):
21+
s = s[b:] + s[:b]
22+
ans = min(ans, s)
23+
return ans
24+
25+
# Add number to just odd or even digits.
26+
def add_a(temp, odd=True):
27+
rv = [str((int(c) + a) % 10) if i %
28+
2 == odd else c for i, c in enumerate(temp)]
29+
return "".join(rv)
30+
31+
ans = "9" * len(s)
32+
odd = s
33+
# Shift Odd digits
34+
for _ in range(10):
35+
odd = add_a(odd, True)
36+
even = odd
37+
38+
# Shift Even digits if applicable
39+
for _ in range(10) if b % 2 else range(1):
40+
ans = get_smaller(ans, even)
41+
even = add_a(even, False)
42+
return ans
43+
44+
# 1440 ms, 68.48%. Same complexity but slow because of overheads
45+
46+
def findLexSmallestString1(self, s: str, a: int, b: int) -> str:
47+
def add(s, a):
48+
return "".join(str((int(c) + a) % 10) if i % 2 else c for i, c in enumerate(s))
49+
50+
def rotate(s, b):
51+
return s[b:] + s[:b]
52+
53+
visited = set()
54+
q = [s]
55+
for s in q:
56+
if s in visited:
57+
continue
58+
visited.add(s)
59+
q.append(add(s, a))
60+
q.append(rotate(s, b))
61+
62+
return min(visited)
63+
64+
65+
# @lc code=end

0 commit comments

Comments
 (0)