Leetcode 75 Blind - Part 1 (1)
Leetcode 75 Blind - Part 1 (1)
1.Two Sum
Question:
Given an array of integers nums and an integer target, return indices of the two numbers such
that they add up to target.
Solution:
Utilize a hash map to store the complement of each number (i.e., target - num) and its index. If a
number’s complement exists in the map, return the indices.
Code (Python):
Explanation:
Iterate through the list, and for each element, calculate its complement with respect to the
target. Check if this complement is already in the hash map. If it is, you’ve found the two
numbers that add up to the target. This approach ensures a time complexity of O(n).
Question:
Given an array prices where prices[i] is the price of a given stock on the i-th day, find the
maximum profit you can achieve by buying and selling once. If no profit is possible, return 0.
Solution:
Track the minimum price encountered so far and calculate the potential profit at each step,
updating the maximum profit accordingly.
Code (Python):
def max_profit(prices):
min_price = float('inf')
max_profit = 0
for price in prices:
min_price = min(min_price, price)
profit = price - min_price
max_profit = max(max_profit, profit)
return max_profit
Explanation:
By keeping track of the lowest price seen so far, you can determine the maximum profit by
comparing the current price with this minimum. This ensures you always buy at the lowest price
and sell at the highest price after the buying day.
3.Contains Duplicate
Question:
Given an integer array nums, return true if any value appears at least twice in the array, and
false if every element is distinct.
Solution:
Use a set to track unique elements. If an element is already in the set, a duplicate exists.
Code (Python):
def contains_duplicate(nums):
seen = set()
for num in nums:
if num in seen:
return True
seen.add(num)
return False
Explanation:
Sets in Python provide O(1) lookup time. By checking if an element is already in the set, you
can efficiently detect duplicates during a single pass through the array.
Question:
Given an integer array nums, return an array answer such that answer[i] is equal to the product
of all the elements of nums except nums[i]. The solution must be in O(n) time and without using
division.
Solution:
Compute the prefix and suffix products for each element and multiply them to get the result.
Code (Python):
def product_except_self(nums):
length = len(nums)
answer = [1] * length
prefix = 1
for i in range(length):
answer[i] = prefix
prefix *= nums[i]
suffix = 1
for i in range(length - 1, -1, -1):
answer[i] *= suffix
suffix *= nums[i]
return answer
Explanation:
First, compute the prefix product for each element, which is the product of all elements before it.
Then, compute the suffix product, which is the product of all elements after it, and multiply it with
the prefix product. This approach avoids division and maintains O(n) time complexity.
5.Maximum Subarray
Question:
Given an integer array nums, find the contiguous subarray (containing at least one number)
which has the largest sum and return its sum.
Solution:
Implement Kadane’s Algorithm, which keeps track of the current maximum subarray sum ending
at each position.
Code (Python):
def max_sub_array(nums):
max_current = max_global = nums[0]
for num in nums[1:]:
max_current = max(num, max_current + num)
max_global = max(max_global, max_current)
return max_global
Explanation:
At each step, decide whether to include the current number in the existing subarray or start a
new subarray. Update the global maximum accordingly. This ensures the maximum subarray
sum is found in linear time.
Question:
Given an integer array nums, find the contiguous subarray within an array (containing at least
one number) which has the largest product.
Solution:
Track both the maximum and minimum product at each position because a negative number
could turn a minimum product into a maximum.
Code (Python):
def max_product(nums):
max_prod = min_prod = result = nums[0]
for num in nums[1:]:
candidates = (num, num * max_prod, num * min_prod)
max_prod = max(candidates)
min_prod = min(candidates)
result = max(result, max_prod)
return result
Explanation:
At every step, consider the current number, the product of the current number and the previous
maximum product, and the product of the current number and the previous minimum product.
This allows us to manage both the effects of positive and negative numbers.
Question:
Suppose an array of length n is sorted in ascending order, then rotated between 1 and n times.
Find the minimum element.
Solution:
Code (Python):
def find_min(nums):
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
if nums[mid] > nums[right]:
left = mid + 1
else:
right = mid
return nums[left]
Explanation:
The smallest value must be in the unsorted half of the array. By comparing nums[mid] with
nums[right], you can discard half of the search space each time, achieving O(log n) time.
Given a rotated sorted array and a target value, return the index if the target is found.
Otherwise, return -1.
Solution:
Modified binary search that accounts for the rotated nature of the array.
Code (Python):
Explanation:
At each step, identify if the left or right half is sorted, and adjust search boundaries accordingly.
You still get O(log n) time.
9.3Sum
Question:
Given an array nums, find all unique triplets such that they sum to zero.
Solution:
def three_sum(nums):
res = []
nums.sort()
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i - 1]:
continue
left, right = i + 1, len(nums) - 1
while left < right:
s = nums[i] + nums[left] + nums[right]
if s < 0:
left += 1
elif s > 0:
right -= 1
else:
res.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
return res
Explanation:
Sorting helps avoid duplicates. Two pointers are used to efficiently check all combinations in
O(n²) time.
Question:
Given n non-negative integers representing the heights of lines on a graph, find two lines that
together with the x-axis form a container that holds the most water.
Solution:
Use the two-pointer approach, starting from the ends of the array.
Code (Python):
def max_area(height):
left, right = 0, len(height) - 1
max_area = 0
while left < right:
max_area = max(max_area, (right - left) * min(height[left], height[right]))
if height[left] < height[right]:
left += 1
else:
right -= 1
return max_area
Explanation:
The area is limited by the shorter line, so move the pointer at the shorter line to try to find a
larger area. This solution runs in O(n) time.
Question:
Calculate the sum of two integers a and b without using the operators + and -.
Solution:
Code (Python):
Explanation:
^ adds bits where there is no carry. & << 1 calculates carry. The loop continues until carry is
zero. It handles both positive and negative integers with masking.
12.Number of 1 Bits
Question:
Write a function that takes an unsigned integer and returns the number of ‘1’ bits (Hamming
weight).
Solution:
Keep flipping the least significant ‘1’ bit to zero and count the number of iterations.
Code (Python):
def hammingWeight(n):
count = 0
while n:
n &= n - 1
count += 1
return count
Explanation:
Each operation n &= n - 1 removes the lowest set bit. Count how many times this happens to
get the total number of ‘1’ bits.
13.Counting Bits
Question:
Given an integer n, return an array ans where ans[i] is the number of 1-bits in the binary
representation of i.
Solution:
Code (Python):
def countBits(n):
res = [0] * (n + 1)
for i in range(1, n + 1):
res[i] = res[i >> 1] + (i & 1)
return res
Explanation:
For every number i, i >> 1 shifts the bits right (removing the last bit), and (i & 1) adds 1 if the last
bit is set. It builds on previously solved subproblems.
14.Missing Number
Question:
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one missing
number.
Solution:
Code (Python):
def missingNumber(nums):
n = len(nums)
return n * (n + 1) // 2 - sum(nums)
Explanation:
The sum of the first n natural numbers is n(n+1)/2. The difference between this and the actual
sum of the array gives the missing number.
15.Reverse Bits
Question:
Solution:
Shift the result left by 1 and add the least significant bit of n.
Code (Python):
def reverseBits(n):
result = 0
for _ in range(32):
result = (result << 1) | (n & 1)
n >>= 1
return result
Explanation:
Extract each bit from n using n & 1, append it to result, and shift n right by one. Repeat this for
all 32 bits.