must-know Flashcards

1
Q

Two Sum

A

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
prevMap = {} #val->index

    for i, n in enumerate(nums):
        difference = target - n
        if difference in prevMap:
            return [prevMap[difference], i]
        prevMap[n] = i
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Three Sum

A

class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []

    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i-1]:
            continue
        l, r = i + 1, len(nums) - 1
        while l < r:
            s = nums[i] + nums[l] + nums[r]
            if s < 0:
                l += 1
            elif s > 0:
                r -= 1
            else:
                res.append([nums[i], nums[l], nums[r]])
                while l < r and nums[l] == nums[l+1]:
                    l += 1
                while l < r and nums[r] == nums[r-1]:
                    r -= 1
                l += 1
                r-= 1
                
    return res
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Longest Consecutive Sequence

A

class Solution:
#group items by sequences, figure it out if there’s left neighbor
#e.g. in [100,4,200,1,3,2], sequences -> [1,2,3,4] , [100] , [200]
#notice how there’s no 0, 99, or 199 AKA one less than seq. AKA no left
#meaning that sequence ONLY STARTS if there’s no left value, so like at 4
#it isn’t start of sequence because there’s a 3 on the left
#O(n) time
def longestConsecutive(self, nums: List[int]) -> int:
numSet = set(nums)
longest_sequence = 0

    for n in nums:
        if (n -1) not in numSet: #check if start of sequence
            length = 0
            while (n + length) in numSet:
                length += 1
            longest_sequence = max(length, longest_sequence)
        
    return longest_sequence
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Contains Duplicate

A

class Solution:
def hasDuplicate(self, nums: List[int]) -> bool:
return len(set(nums)) < len(nums)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Valid Palindrome

A

class Solution:
def isPalindrome(self, s: str) -> bool:
newStr = ‘’
for c in s:
if c.isalnum():
newStr += c.lower()
return newStr == newStr[::-1]

/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function(s) {
const cleanStr = s.toLowerCase().replace(/[^a-z0-9]/g, ‘’);
const reversedStr = cleanStr.split(‘’).reverse().join(‘’);
return cleanStr === reversedStr;
};

// Test cases
function testIsPalindrome() {
console.log(“Test 1 Passed:”, isPalindrome(“A man, a plan, a canal: Panama”) === true);
console.log(“Test 2 Passed:”, isPalindrome(“race a car”) === false);
console.log(“Test 3 Passed:”, isPalindrome(“ “) === true); // considering empty string or spaces as palindromes
console.log(“Test 4 Passed:”, isPalindrome(“12321”) === true);
console.log(“Test 5 Passed:”, isPalindrome(“123456”) === false);
}

testIsPalindrome();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Valid Anagram

A

class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False

    count = [0] * 26
    for i in range(len(s)):
        count[ord(s[i]) - ord('a')] += 1
        count[ord(t[i]) - ord('a')] -= 1

    for val in count:
        if val != 0:
            return False

    return True
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Group Anagrams

A

class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
res = defaultdict(list) #map char count to list of anagrams

    for s in strs:
        count = [0] * 26 # a...z

        for c in s:
            count[ord(c) - ord("a")] += 1 #ascii values
        res[tuple(count)].append(s)

    return list(res.values())
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Top K Frequent Elements

A

class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
#O(n) -> modified bucket sort, table example:
#i (count) : 0 1 2 …
#values : [10] [2] [4,2] …
#this is better because the i(count) row is always size of array, always
#bounded, never wasting time/space
count = {} #hashmap
frequencies = [[] for i in range(len(nums) + 1)] #size of input + 1

    for n in nums:
        count[n] = 1 + count.get(n,0)
    for n, c in count.items(): #for every number and count
        frequencies[c].append(n)

    result = []

    for i in range(len(frequencies) - 1, 0, -1): #descending order to find top k 
        for n in frequencies[i]:
            result.append(n) #append most freq
            if len(result) == k:
                return result
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Product of Array Except Itself

A

class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
total_product = 1
zero_count = 0
n = len(nums)

    for num in nums:
        if num != 0:
            total_product *= num
        else:
            zero_count += 1
    
    if zero_count > 1:
        return [0] * n
    elif zero_count == 1:
        result = []
        for num in nums:
            if num == 0:
                result.append(total_product)
            else:
                result.append(0)
        return result
    else:
        result = [total_product // num for num in nums]
        return result

class Solution:
def productExceptSelf(self, nums):
res, p = [1] * len(nums), 1
for i in range(len(nums)): res[i], p = p, p * nums[i]
p = 1
for i in range(len(nums) - 1, -1, -1): res[i], p = res[i] * p, p * nums[i]
return res

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Valid Parenthesis

A

O(n^2)

class Solution:
def isValid(self, s: str) -> bool:
while ‘()’ in s or ‘{}’ in s or ‘[]’ in s:
s = s.replace(‘()’, ‘’)
s = s.replace(‘{}’, ‘’)
s = s.replace(‘[]’, ‘’)
return s == ‘’

class Solution:
def isValid(self, s: str) -> bool:
stack = []
# Create a mapping of closing parentheses to opening parentheses
mapping = {‘)’: ‘(‘, ‘}’: ‘{‘, ‘]’: ‘[’}

    for char in s:
        if char in mapping:
            # If the stack is empty or the top of the stack doesn't match the corresponding opening parenthesis
            top_element = stack.pop() if stack else '#'
            if top_element != mapping[char]:
                return False
        else:
            # Push the opening parenthesis onto the stack
            stack.append(char)
    
    # If the stack is empty, all parentheses are valid
    return not stack #O(n)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Best Time to Buy and Sell Stock

A

class Solution:
#init left ptr on day one, right ptr on day two
def maxProfit(self, prices: List[int]) -> int:
l, r = 0, 1 #left is buying, right is selling
max_profit = 0

    while r < len(prices):
        if prices[l] < prices[r]: #check if profitable
            profit = prices[r] - prices[l]
            max_profit = max(profit, max_profit)
        else:
            l = r #shift all the way to the right; we found the lowest price
        r += 1

    return max_profit
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Longest Substring without Repeated Characters

A

class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
char_set = set()
l = 0
result = 0

    for r in range(len(s)):
        while s[r] in char_set: #duplicate
            char_set.remove(s[l])
            l += 1
        char_set.add(s[r])
        result = max(result, r-l + 1)

    return result

class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
left = 0
seen = {}
output = 0

    for right, curr in enumerate(s):
        if curr in seen:
            left = max(left, seen[curr] + 1)
        output = max(output, right - left + 1)
        seen[curr] = right

    return output
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Longest Repeating Character Replacement

A

class Solution:
#hashmap/array to count occurences of char
#do window length - count[each index] to figure out with window/substring, which
#needs to be replaced
def characterReplacement(self, s: str, k: int) -> int:
count = {}
res = 0

    l = 0
    maxf = 0
    for r in range(len(s)):
        count[s[r]] = 1 + count.get(s[r], 0)
        maxf = max(maxf, count[s[r]])

        while (r - l + 1) - maxf > k:
            count[s[l]] -= 1
            l += 1
        res = max(res, r - l + 1)

    return res
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Permutation in String

A

class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
if len(s1) > len(s2):
return False

    s1count = [0] * 26
    s2count = [0] * 26

    for i in range(len(s1)): #init freq counts for s1 and 1st window in s2
        s1count[ord(s1[i]) - ord('a')] += 1
        s2count[ord(s2[i]) - ord('a')] += 1

    for i in range(len(s2) - len(s1)): #slide window over s2
        if s1count == s2count:
            return True
        s2count[ord(s2[i]) - ord('a')] -= 1
        s2count[ord(s2[i + len(s1)]) - ord('a')] += 1

    return s1count == s2count #check last window
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Minimum Window Substring

A

class Solution:
def minWindow(self, s: str, t: str) -> str:
if len(s) < len(t):
return “”

    char_count = defaultdict(int) #store A-Z and put val 1 if in substr, or -1 if not
    for ch in t:
        char_count[ch] += 1

    target_chars_remaining = len(t) #go thru s, see at each index if it equals t, subtract this
    min_window = (0, float("inf")) #0 to infinity just to init
    start_index = 0

    for end_index, ch in enumerate(s):
        if char_count[ch] > 0: #if value of s is present in dict, AKA if its 1
            target_chars_remaining -= 1 #one less char we need to find from substr
        char_count[ch] -= 1

        if target_chars_remaining == 0:
            while True:
                char_at_start = s[start_index]
                if char_count[char_at_start] == 0:
                    break
                char_count[char_at_start] += 1
                start_index += 1
            if end_index - start_index < min_window[1] - min_window[0]:
                min_window = (start_index, end_index)
            
            char_count[s[start_index]] += 1
            target_chars_remaining += 1
            start_index += 1

    return "" if min_window[1] > len(s) else s[min_window[0]:min_window[1]+1]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Merge K Sorted Lists

A

Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:

    nodes = []

    for node in lists:
        while node:
            nodes.append(node)
            node = node.next
        
    
    nodes.sort(key = lambda x: x.val)

    dummy = ListNode()
    i = dummy

    for node in nodes:
        i.next = node
        i = i.next
    
    i.next = None

    return dummy.next
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Container With the Most Water

A

class Solution:
def maxArea(self, heights: List[int]) -> int:
left, right = 0, len(heights)-1
res = 0

    while left < right:
        area = min(heights[left], heights[right]) * (right-left)
        res = max(res,area)
        if heights[left] <= heights[right]:
            left += 1
        else:
            right -= 1
    
    return res
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Merge Intervals

A

class Solution:
#input arrays within the big intervals list might not be sorted
#interval must be from 0…infinity
#go thru the start indices, i.e. list[0][0], list[1][0], …, list[4][0], …
#while at the same time oppositely comparing with end indices, i.e. list[-1][1]
#O(n log n)
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key = lambda i : i[0]) #sorting by all start interval values
output = [intervals[0]] #avoid edge case

    for start, end in intervals[1:]: #skip first
        lastEnd = output[-1][1] #end value of most recent interval
        if start <= lastEnd: #overlapping
            output[-1][1] = max(lastEnd, end)
            #e.g. in [1,5] , [2,4]
            #we want to keep the 5 from the first when merging
        else:
            output.append([start,end])
            #e.g. [1,5] , [7,8] = [1,5] , [7,8] -> equals itself, already sorted

    return output
19
Q

Largest Number

A

class Solution:
def largestNumber(self, nums: List[int]) -> str:
return ‘‘.join(sorted(map(str, nums), key=lambda s: s * 10, reverse=True)) if any(nums) else “0”

20
Q

Binary Search

A

class Solution:
def search(self, nums: List[int], target: int) -> int:
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1

21
Q

Search a 2D Matrix

A

class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
rows, cols = len(matrix), len(matrix[0])
left, right = 0, rows * cols - 1

    while left <= right:
        mid = (left + right) // 2
        row, col = mid // cols, mid % cols
        guess = matrix[row][col]

        if guess == target:
            return True
        if guess < target:
            left = mid + 1
        else:
            right = mid - 1

    return False
22
Q

Find Minimum in Rotated Sorted Array

A

class Solution:
def findMin(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1

    while left < right:
        mid = (left + right) // 2
        if nums[mid] <= nums[right]:
            right = mid
        else:
            left = mid + 1

    return nums[left]
23
Q

Reverse Linked List

A

Definition for singly-linked list.
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next

class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
previous = None
current = head
while current:
next_node = current.next
current.next = previous
previous = current
current = next_node
return previous

24
Q

Merge Two Sorted Lists

A

Definition for singly-linked list.
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next

class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
temp = ListNode()
node = ListNode()
temp = node

        while list1 and list2:
            if list1.val < list2.val:
                node.next = list1
                list1 = list1.next
            else:
                node.next = list2
                list2 = list2.next
            node = node.next

        node.next = list1 or list2

        return temp.next
25
Linked List Cycle Detector
Definition for singly-linked list. # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: current = head visited = [] while current: if current.next in visited: return True else: visited.append(current) current = current.next return False
26
Remove Nth Node From End of List
Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: fast = head slow = head for i in range(n): fast = fast.next if not fast: return head.next while fast.next: slow = slow.next fast = fast.next slow.next = slow.next.next return head
27
Implement Queue Using Stacks
class MyQueue: def __init__(self): self.input = [] self.output = [] def push(self, x: int) -> None: self.input.append(x) def pop(self) -> int: self.peek() #ensure output has current front return self.output.pop() def peek(self) -> int: if not self.output: while self.input: self.output.append(self.input.pop()) return self.output[-1] def empty(self) -> bool: return not self.input and not self.output Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()
28
Daily Temperatures
class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: res = [0] * len(temperatures) stack = [] for i, temp in enumerate(temperatures): while stack and temperatures[stack[-1]] < temp: index = stack.pop() res[index] = i - index stack.append(i) return res
29
Number of Islands
class Solution: def numIslands(self, grid: List[List[str]]) -> int: if not grid: return 0 rows, cols = len(grid), len(grid[0]) visited = set() islands = 0 #count number of islands def bfs(r,c): #iterative, NOT RECURSIVE queue = collections.deque() #normally used for bfs visited.add((r,c)) queue.append((r,c)) while queue: #while queue not empty/not at end row, col = queue.popleft() #if you change to just pop, it'll be dfs directions = [[1, 0], [-1, 0], [0, 1], [0, -1]] #right,left,up,down for dr, dc in directions: #for row, col in directions r, c = row + dr, col + dc if (r in range(rows) #check if in range of rows and c in range(cols) #check if in range of cols and grid[r][c] == "1" #check if this is a land position and (r, c) not in visited): #check if not visited already queue.append((r,c)) visited.add((r,c)) for r in range(rows): #iterate rows for c in range(cols): #iterate cols if grid[r][c] == "1" and (r,c) not in visited: #not visited yet, #avoids repetition bfs(r, c) islands += 1 return islands
30
Clone Graph
""" # Definition for a Node. class Node: def __init__(self, val = 0, neighbors = None): self.val = val self.neighbors = neighbors if neighbors is not None else [] """ from typing import Optional class Solution: def cloneGraph(self, node: Optional['Node']) -> Optional['Node']: if not node: return None visited = {} queue = deque([node]) visited[node] = Node(node.val) #copy of starting node, add to visited while queue: curr_node = queue.popleft() for neighbor in curr_node.neighbors: if neighbor not in visited: visited[neighbor] = Node(neighbor.val) queue.append(neighbor) visited[curr_node].neighbors.append(visited[neighbor]) return visited[node]
31
Course Schedule
class Solution: #just do dfs to see if the "end" node doesn't point to anything (cycle detection) #use adj list -> for each course, list all prereqs #basically, look thru adj list and see if the "end" has empty prereq list #then, that means we can complete it #also, use set to store current visited node (for cycles) def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: preMap = {i: [] for i in range(numCourses)} for courses, prereq in prerequisites: preMap[courses].append(prereq) #add data to map #visitSet stores all courses along the current DFS path visitSet = set() def dfs(course): if course in visitSet: #cycle detected, course cannot be completed return False if preMap[course] == []: #can be taken return True visitSet.add(course) for prereq in preMap[course]: if not dfs(prereq): #if return false return False visitSet.remove(course) preMap[course] = [] #update adj list return True for course in range(numCourses): #now call dfs if not dfs(course): return False return True
32
Subsets
class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: res = [[]] for num in nums: res += [curr + [num] for curr in res] return res
33
Combination Sum
class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: dp = [[] for _ in range(target+1)] for c in candidates: for i in range(c, target+1): if i == c: dp[i].append([c]) for comb in dp[i-c]: dp[i].append(comb + [c]) return dp[-1]
34
Kth Largest Element in Array
class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: min_value = min(nums) max_value = max(nums) count = [0] * (max_value - min_value + 1) for num in nums: count[num - min_value] += 1 remaining = k for i in range(len(count) - 1, -1, -1): remaining -= count[i] if remaining <= 0: return i + min_value
35
Task Scheduler
class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: #greedy freq = [0] * 26 for task in tasks: freq[ord(task) - ord('A')] += 1 freq.sort() chunk = freq[25] - 1 idle = chunk * n for i in range(24, -1, -1): idle -= min(chunk, freq[i]) return len(tasks) + idle if idle >=0 else len(tasks)
36
Jump Game
class Solution: #greedy -> O(n) #change the goal from reverse order, so if we see [...1,4] we know for sure we #can get to last value "4" because prev index had "1" step that we can exactly #take to end, so then we'd update goal to "1" and keep going def canJump(self, nums: List[int]) -> bool: goal = len(nums)-1 #end for i in range(len(nums)-1, -1, -1): if i + nums[i] >= goal: #is jump length >= goal? then shift goal lefter goal = i return True if goal == 0 else False #0 means jump was able to be completed
37
Coin Change
class Solution: #you can use the coins arr unlimited time (e.g. in [1,2] you can do 2*6 if the #amount if 12) #use cache "dp" to avoid doing calculations more than once def coinChange(self, coins: List[int], amount: int) -> int: dp = [amount+1] * (amount+1) #we want 0....amount dp[0]=0 for a in range(1, amount+1): #bottom-up for c in coins: if a - c >= 0: dp[a]= min(dp[a], 1+dp[a-c]) #e.g. if coin is 4 and amount is 7, then dp[7] = 1 + dp[3], #because 7-4=3 so its a possible solution return dp[amount] if dp[amount] != amount + 1 else -1 #if value isn't #default if amount == 0: return 0
38
Climbing Stairs
class Solution: #dynamic programming -> store an array "dp" to store how mnay ways we can take #steps to result/last step, go right to left and store in each index (last two #indices will always be one because only one step to goal, and goal is at itself), #basically then keep adding every 2 right values to get current index #kinda like fibonacci seq def climbStairs(self, n: int) -> int: one, two = 1, 1 for i in range(n-1): temp = one one = one + two two = temp return one
39
Rotate Array
class Solution: def rotate(self, matrix: List[List[int]], k: int) -> None: k = k % len(matrix) if k != 0: matrix[:k], matrix [k:] = matrix[-k:], matrix[:-k] class Solution: def rotate(self, matrix: List[List[int]], k: int) -> None: # Flatten the matrix flat = [elem for row in matrix for elem in row] # Rotate the flattened list (1D array) k = k % len(flat) if k != 0: flat = flat[-k:] + flat[:-k] # Fill the matrix back with rotated values for i in range(len(matrix)): matrix[i] = flat[i * len(matrix[0]):(i + 1) * len(matrix[0])]
40
Gas Station
class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: #O(n) -> greedy if sum(gas) < sum(cost): return -1 result_index = 0 total = 0 for i in range(len(gas)): total += gas[i] - cost[i] if total < 0: total = 0 result_index = i+1 return result_index
41
H-Index
class Solution: def hIndex(self, citations: List[int]) -> int: n = len(citations) citations.sort() for i,v in enumerate(citations): if n - i <= v: return n - i return 0
42
Roman to Integer
class Solution: def romanToInt(self, s: str) -> int: values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} total = 0 for i in range(len(s)): if i+1 < len(s) and values[s[i]] < values[s[i+1]]: total -= values[s[i]] else: total += values[s[i]] return total
43
Integer to Roman
class Solution: def intToRoman(self, num: int) -> str: hashset = {1000: "M", 900: "CM", 500: "D", 400: "CD", 100: "C", 90: "XC", 50: "L", 40: "XL", 10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I"} result = "" for value, symbol in hashset.items(): while num >= value: result += symbol num -= value return result
44
Length of Last Word
class Solution: def lengthOfLastWord(self, s: str) -> int: return len((s.strip()).split()[-1])