Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
from typing import List


class Solution:
def validSequence(self, word1: str, word2: str) -> List[int]:
"""
Find the lex-smallest strictly increasing index sequence in word1 whose
picked characters form a string almost-equal to word2 (at most one change).

Approach:
1. Greedily match word2 as a subsequence of word1 from the right.
last[j] = index used for word2[j] in that rightmost exact match.
last[j..] is therefore the rightmost way to match suffix word2[j:].
2. Scan left-to-right building the lex-smallest answer:
- Prefer an exact match for word2[j].
- On mismatch, use our one allowed change at the earliest safe index:
safe iff the remaining suffix word2[j+1:] still has a rightmost
match entirely after i (i < last[j+1]), or j is the last char.
"""
m = len(word2)
last = [-1] * m

i, j = len(word1) - 1, m - 1
while i >= 0 and j >= 0:
if word1[i] == word2[j]:
last[j] = i
j -= 1
i -= 1

ans: List[int] = []
can_skip = True
j = 0
for i, c in enumerate(word1):
if j == m:
break
if c == word2[j]:
ans.append(i)
j += 1
elif can_skip and (j == m - 1 or i < last[j + 1]):
# Use the single allowed change here; rest must match exactly.
can_skip = False
ans.append(i)
j += 1

return ans if j == m else []


if __name__ == "__main__":
sol = Solution()
tests = [
("vbcca", "abc", [0, 1, 2]),
("bacdc", "abc", [1, 2, 4]),
("aaaaaa", "aaabc", []),
("abc", "ab", [0, 1]),
("xabc", "yabc", [0, 1, 2, 3]),
("cab", "xab", [0, 1, 2]),
("aabc", "abc", [0, 1, 3]), # skip at index 1 is lex-smaller than exact [0,2,3]
("xbca", "abc", [0, 1, 2]),
]
for word1, word2, expected in tests:
got = sol.validSequence(word1, word2)
status = "OK" if got == expected else "FAIL"
print(f"{status}: word1={word1!r} word2={word2!r} -> {got} (expected {expected})")
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from typing import List


class Solution:
def maximumProduct(self, nums: List[int]) -> int:
"""
628. Maximum Product of Three Numbers

After sorting, the max product of three numbers is the larger of:
1) three largest values (all positive, or least-negative if all negative)
2) two smallest (most negative) * largest (neg*neg*pos can dominate)

Time: O(n log n)
Space: O(1) extra if sort is in-place (O(n) depending on sort impl)
"""
nums.sort()
return max(
nums[-1] * nums[-2] * nums[-3],
nums[0] * nums[1] * nums[-1],
)


if __name__ == "__main__":
s = Solution()
assert s.maximumProduct([1, 2, 3]) == 6
assert s.maximumProduct([1, 2, 3, 4]) == 24
assert s.maximumProduct([-1, -2, -3]) == -6
assert s.maximumProduct([-4, -3, -2, -1, 60]) == 720
assert s.maximumProduct([-100, -98, -1, 2, 3, 4]) == 39200
assert s.maximumProduct([-1, -2, 1, 2, 3]) == 6
assert s.maximumProduct([0, 0, 0]) == 0
assert s.maximumProduct([-5, 0, 1, 2]) == 0
print("ok")
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from typing import List


class Solution:
def maxProduct(self, nums: List[int]) -> int:
# (a-1)*(b-1) is maximized by the two largest values (nums[i] >= 1).
max1 = max2 = 0
for num in nums:
if num > max1:
max2, max1 = max1, num
elif num > max2:
max2 = num
return (max1 - 1) * (max2 - 1)
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from typing import List


class Solution:
def uniqueXorTriplets(self, nums: List[int]) -> int:
"""
Count distinct values of nums[i] ^ nums[j] ^ nums[k] over i <= j <= k.

Key insight: index reuse (i==j or j==k) only produces values already in
the array. Every triple of values (a, b, c) from the distinct set U is
achievable, so the answer is |{a ^ b ^ c : a, b, c in U}|.

nums[i] <= 1500 => XOR results fit in [0, 2047]. Build all pairwise XORs,
then XOR each with every value in U.
"""
# Presence of values; range is small
present = [False] * 2048
for x in nums:
present[x] = True
vals = [x for x in range(2048) if present[x]]

# All pairwise XORs a ^ b for a, b in U (includes a ^ a == 0)
pair = [False] * 2048
for i, a in enumerate(vals):
for b in vals[i:]:
pair[a ^ b] = True
pair_vals = [x for x in range(2048) if pair[x]]

# All triple XORs (a ^ b) ^ c
trip = [False] * 2048
for p in pair_vals:
for c in vals:
trip[p ^ c] = True

return sum(trip)
54 changes: 54 additions & 0 deletions leetcode/shift_2d_grid/shift_2d_grid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from typing import List


class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
"""
1260. Shift 2D Grid

Treat the m x n grid as a flattened 1D array of length m*n.
One shift is a right-rotate by 1 in that array (last -> first).
After k shifts, element at flat index i moves to (i + k) % (m*n).

Time: O(m * n)
Space: O(m * n) for the result
"""
m, n = len(grid), len(grid[0])
total = m * n
k %= total
ans = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
ni, nj = divmod((i * n + j + k) % total, n)
ans[ni][nj] = grid[i][j]
return ans


if __name__ == "__main__":
s = Solution()
assert s.shiftGrid([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 1) == [
[9, 1, 2],
[3, 4, 5],
[6, 7, 8],
]
assert s.shiftGrid([[3, 8, 1, 9], [19, 7, 2, 5], [4, 6, 11, 10], [12, 0, 21, 13]], 4) == [
[12, 0, 21, 13],
[3, 8, 1, 9],
[19, 7, 2, 5],
[4, 6, 11, 10],
]
assert s.shiftGrid([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 9) == [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
assert s.shiftGrid([[1], [2], [3], [4], [5], [6], [7]], 23) == [
[6],
[7],
[1],
[2],
[3],
[4],
[5],
]
print("ok")