Problems Solved:
- #1 Two Sum
- #217 Contains Duplicate
π‘ What I Learned
Today, I focused on practicing basic array operations in both Python and C++.
Key takeaways:
-
Python: Learned how to use
set
for quick duplicate checks. -
C++: Reinforced understanding of
vector
for arrays andunordered_set
for constant-time lookups.
π Problem #1 β Two Sum
Goal: Find indices of two numbers in the array that add up to a given target.
Python Solution:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for z in range(0, len(nums)):
for i in range(z + 1, len(nums)):
if (nums[z] + nums[i]) == target:
return [z, i]
Logic:
- Loop through all elements with index
z
. - For each element, check all following elements with index
i
. - If their sum equals the target, return the two indices.
- Time complexity: O(nΒ²) because of the nested loop.
C++ Solution:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int x = 0;
int max = nums.size();
for (x; x < max; x++) {
for (int y = x + 1; y < max; y++) {
if ((nums[x] + nums[y]) == target) {
return {x, y};
}
}
}
return {};
}
};
Logic:
- Iterate over
nums
with indexx
. - Inner loop starts from
x + 1
to avoid repeating pairs. - If
nums[x] + nums[y]
equalstarget
, return the pair{x, y}
. - Time complexity: O(nΒ²), same as Python version.
π Problem #217 β Contains Duplicate
Goal: Return true
if any number appears more than once in the array.
Python Solution:
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return len(nums) != len(set(nums))
Logic:
- Convert
nums
into aset
(removes duplicates). - If the size changes, there was at least one duplicate.
-
Time complexity: O(n) on average because
set
operations are constant time.
C++ Solution:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> seen;
for (int num : nums) {
if (seen.count(num)) {
return true;
}
seen.insert(num);
}
return false;
}
};
Logic:
- Use an
unordered_set
to store numbers seen so far. - For each number:
- If it already exists in
seen
, returntrue
. - Otherwise, insert it into the set.
-
Time complexity: O(n) on average because
unordered_set
lookups and insertions are constant time.
-
Time complexity: O(n) on average because
πΈ Achievements
- Two Sum (Python & C++):
- Contains Duplicate (Python & C++):
π¦ Complexity Recap
-
Two Sum:
O(nΒ²)
(brute force nested loop) -
Contains Duplicate:
O(n)
(hash set lookups)
π’ Join the Journey
Iβve just started this LeetCode adventure, solving problems in both Python and C++ while sharing my learnings.
If youβre interested in algorithms, data structures, or just want to keep up with my progress β stay tuned and join me on this journey!
π Connect with me:
Top comments (0)