Skip to content

Instantly share code, notes, and snippets.

@Khamies
Khamies / 2Sum-bruteforce.py
Last active February 15, 2023 08:24
Brute Force Solution for 2Sum Problem.
def two_sum(nums, target):
n = len(nums)
for i in range(n):
for j in range(i + 1, n): # we start the second loop from j = i+1.
if nums[i] + nums[j] == target:
return [i, j]
return []
@Khamies
Khamies / 2Sum_optimized.py
Last active February 10, 2023 08:43
An optimized solution for 2Sum problem.
def twoSum(nums, target):
mapper = {}
for i, e in enumerate(nums):
# Store the numbers inside the hashmap,
# where the keys are the numbers,
# and the values are the coressponding indicies.
mapper[e] = i
def three_sum_brute(nums):
nums = sorted(nums) # sort nums.
n = len(nums)
target = 0
result = set()
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
def three_sum_optimized(nums):
nums = sorted(nums)
n = len(nums)
result = set()
for i in range(n):
left = i + 1
right = n - 1
@Khamies
Khamies / 4Sum-optimized.py
Last active February 12, 2023 01:22
An Optimized Solution for 4Sum Problem
def fourSum(nums, target):
nums = sorted(nums)
n = len(nums)
result = set()
for i in range(n): # first loop
second_taget = target - nums[i] # target 2
for j in range(i + 1, n): # second loop
third_target = second_taget - nums[j] # target 3
def letterCombinations(digits):
hashmap = {
"1": "None",
"2": ["a", "b", "c"],
"3": ["d", "e", "f"],
"4": ["g", "h", "i"],
"5": ["j", "k", "l"],
"6": ["m", "n", "o"],
"7": ["p", "q", "r", "s"],
def letterCombinations(digits):
hashmap = {
"1": "None",
"2": ["a", "b", "c"],
"3": ["d", "e", "f"],
"4": ["g", "h", "i"],
"5": ["j", "k", "l"],
"6": ["m", "n", "o"],
"7": ["p", "q", "r", "s"],
def generateParenthesis(n):
def generate(opening_count, closing_count, path, result):
# Constraint 1
if opening_count > closing_count:
return
# Constraint 2
if opening_count < 0:
return
# Constraint 3
if closing_count < 0:
def generateParenthesis(n):
# Create is_valid parenthesis to check if a parenthesis is
# well-formed.
def is_valid_parenthesis(string):
if len(string) < 2:
return False
def max_water_area(height):
n = len(height)
area = 0
for i in range(n):
for j in range(i + 1, n):
h = min(height[i], height[j])
w = j - i
area = max(area, h * w)