Today's coding session was focused on strengthening my understanding of three important algorithmic patterns that frequently appear in technical interviews.
β 1. Robot Return to Origin (LeetCode 657)
Pattern: Simulation
Tracked the robot's coordinates (x, y) after every move and simply checked whether it returned to the origin.
class Solution:
def judgeCircle(self, moves: str) -> bool:
x = y = 0
for move in moves:
if move == "U":
y += 1
elif move == "D":
y -= 1
elif move == "L":
x -= 1
else:
x += 1
return x == 0 and y == 0
Complexity
- β±οΈ Time: O(n)
- πΎ Space: O(1)
β 2. Max Consecutive Ones III (LeetCode 1004)
Pattern: Sliding Window
Maintained a window containing at most k zeros. Whenever the number of zeros exceeded k, I shrank the window from the left.
class Solution:
def longestOnes(self, nums, k):
left = 0
zeros = 0
for right in range(len(nums)):
if nums[right] == 0:
zeros += 1
while zeros > k:
if nums[left] == 0:
zeros -= 1
left += 1
return right - left + 1
Complexity
- β±οΈ Time: O(n)
- πΎ Space: O(1)
β 3. Candy (LeetCode 135)
Pattern: Greedy Algorithm
Used two passes:
- Left β Right
- Right β Left
This guarantees the minimum candies while satisfying both neighbor conditions.
class Solution:
def candy(self, ratings):
n = len(ratings)
candies = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i - 1]:
candies[i] = candies[i - 1] + 1
for i in range(n - 2, -1, -1):
if ratings[i] > ratings[i + 1]:
candies[i] = max(candies[i], candies[i + 1] + 1)
return sum(candies)
Complexity
- β±οΈ Time: O(n)
- πΎ Space: O(n)
π‘ Key Takeaways
βοΈ Simulation problems become straightforward when you model the state correctly.
βοΈ Sliding Window is one of the most powerful techniques for optimizing subarray problems from O(nΒ²) to O(n).
βοΈ Greedy algorithms work best when making the optimal local decision leads to a globally optimal solution.
Every day of consistent DSA practice helps me improve my problem-solving mindset, write more efficient code, and deepen my understanding of algorithms.
Looking forward to solving the next set of LeetCode challenges! π
Top comments (0)