LeetCode Practice Reflection - 1. Two Sum
Date:
19MAY25
What I Worked on Today:
Practiced doing LeetCode Problem 1.Two Sum.
What I Learned:
- How to use the enumerate() function
- How to optimize possible solutions after considering brute force methods
- How to declare a new dictionary (key value pair)
Code Snippet I Wrote or Studied:
class Solution(object):
def twoSum(self, nums, target):
seen = {}
for i, num in enumerate(nums):
compliement = target - num
if compliment in seen:
return [seen[compliment], i]
seen[num] = i
In My Own Words:
This function takes in a list of numbers and will return the index of the two numbers that add up to the provided target value. The way this program works is that it creates a dictionary called "seen". It will then iterate through the list of numbers and use the enumerate function to keep track of the index and the value of the specific item in the provided list. The for loop will calculate the compliment number, meaning the target value minus the current number. It will then check to see if the value exists in the dictionary. If it does the indexes for both numbers will be returned. If the number is not found, it's value and index are added to the dictionary and the for loop will continue on.
What Was Difficult or Confusing:
My first iteration was using brute force to compare each number to every other number to find the target pair. This is an O(n^2) operation which is very inefficient. There was a more efficient method, but I could not figure it out.
How I Solved It:
I used several online resources to learn about the key data structure being a dictionary. This data structure used a key value pair to map one piece of data to another. This in conjunction with the enumerate function allowed me develop a solution that runs in approximately O(n) time. There are some additional memory requirements as a new dictionary needs to be created, but in my opinion the trade off is worth the improvement in time complexity.
Next Steps:
I will continue to explore the LeetCode problem website to develop my programming and critical thinking skills.
Comments
Post a Comment