Fundamentals Flashcards

1
Q

Longest Palindromic Substring (DP)

Find the longest palindrome in a string. s =”cbbd”

A
dp = [[False] * m for _ in range(m)]

for i in range(m):
    dp[i][i] = True
		start = 0
		max_len = 1
for length in range(2, m+1):
    for i in range(m-length+1):
		    j = i + length -1
				    if s[i] == s[j] and (length == 2 or dp[i+1][j-1]):
						    dp[i][j] = True
								if length > max_len:
								    start = i
										max_len = length
return s[start:start+max_len]

Have a bool dp to track the palindromes. Check the palindromes for len.

Check first and last chars of the current length and look up dp to see if what’s in between is a palindrome.

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

Longest Common Subsequence (DP)

Find the longest common subsequence between two strings.

str1 = “abcde”, str2 = “ace”

A
m = len(str1)
n = len(str2)
dp = [[0] * (n+1) for _ in range(m+1)

for i in range(1, m+1):
    for j in range(1, n+1):
		    if str1[i-1] == str2[j-1]:
				    dp[i][j] = dp[i-1][j-1] + 1
	      else:
				    dp[i][j] = max(dp[i-1][j], dp[i][j-1])
						
	return dp[m][n]

Track how many characters the two strings have in common.

Increase count while you find chars in common. If the current position is not a match, update the dp with the max from either of the previous positions ([i-1][j], or [i][j-1])

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

Unique Number of Occurences

Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise.

A
hash_map = {}
for item in arr:
    hash_map.setdefault(item, 0)
    hash_map[item] += 1
		
return len(list(hash_map.values)) == len(list(set(hash_map.values)))

Store the number of occurences of each item in a hash map. Using the built in setdefault function is ideal. Return a length array which is created by the values of the hash map compared to its set.

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

Check If String Is a Prefix of Array

Given a string s and an array of strings words, determine whether s is a prefix string of words.

A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length.

Return true if s is a prefix string of words, or false otherwise.

A
comparison_str = ""
for word in words:
    comparison_str += word
    if len(comparison_str) > len(s):
		    return False
		if comparison_str == s:
		    return True
return False

Create a string to compare the words to the given string s. Append each word one by one to this comparison_str and check if the length of this comparison string exceeded the length of the given string or if they are equal.

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

Valid Parantheses

Given a string s containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

A
stack = []
hash_map = {")":"(", "]":"[", "}":"{"}
for character in s:
    if not stack:
		    stack.append(character)
		elif character in hash_map:
		    if hash_map[character] == stack[-1]:
				    stack.pop()
				else:
				    return False
		else:
				  stack.append(character)
return len(stack) == 0
		    
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Backspace String Compare

Given two strings s and t, return true if they are equal when both are typed into empty text editors. ‘#’ means a backspace character.

Note that after backspacing an empty text, the text will continue empty.

A
stack_1 = []
stack_2 = []

for char in s:
    if char != "#":
        stack_1.append(char)
		elif stack_1:
		    stack_1.pop()
for char in t:
    if char != "#":
        stack_2.append(char)
		elif stack_2:
		    stack_2.pop()				
				
return stack_1 == stack_2

“If you encounter a “#” pop the last element. If there’s no element in the stack simply continue.”

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

Minimum String Length After Removing Substrings

You are given a string s consisting only of uppercase English letters.

You can apply some operations to this string where, in one operation, you can remove any occurrence of one of the substrings “AB” or “CD” from s.

Return the minimum possible length of the resulting string that you can obtain.

Note that the string concatenates after removing the substring and could produce new “AB” or “CD” substrings.

A
stack = []

for char in s:
    if not stack:
        stack.append(char)
    if (stack[-1] == "A" and char == "B") or (stack[-1] == "C" and char == "D"):
		    stack.pop()
    else:
		    stack.append(char)
				
return len(stack)

“Go through the string char by char append until you encounter the sequence you are looking for. If you have the sequence that you are looking for pop and continue”.

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

Removing Stars From a String

You are given a string s, which contains stars *.

In one operation, you can:

Choose a star in s.
Remove the closest non-star character to its left, as well as remove the star itself.
Return the string after all stars have been removed.

Note:

The input will be generated such that the operation is always possible.
It can be shown that the resulting string will always be unique.

A
stack = []

for char in s: 
    if char != "*":
        stack.append(char)
    elif stack: 
        stack.pop()
str = ""
while stack:
    str += stack.pop()

str = str[::-1]

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

Sort Array by Increasing Frequency

Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order.

Return the sorted array.

A
hash_map = {}
result =[]

for num in nums: 
    if num not in hash_map:
        hash_map[num] = 1
    else:
        hash_map[num] += 1
return sorted(nums, key = lambda x: (hash_map[x], -x))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Find Subsequence of Length K With the Largest Sum

You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum.

Return any such subsequence as an integer array of length k.

A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

A
min_heap = []
top_k_indices = []
for idx, val in enumerate(nums):
    heapq.heappush(min_heap, (val, idx))
    if len(max_heap) > k:
		    heapq.heappop(min_heap)
while min_heap:
   _, idx = heapq.heappop(min_heap)
	 top_k_indices.append(idx)

top_k_indices.sort()

for idx in top_k_indices:
    result.append(nums[idx])

return result
    

Use min heap to store the values. Pop the smallest element each time the size gets greater than k. In the end you will end up with the largest k elements.

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

K Closest Points to Origin

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).

The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).

You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).

A
import heapq

max_heap = []
result =[]
for idx, point in enumerate(points):
    temp_val = sqrt(point[0]**2 + point[1]**2)
		heapq.heappush(max_heap, (-temp_val, idx))
		if len(max_heap) > k:
		    heapq.heappop(max_heap)
for item in max_heap:
    _, idx = item
		result.append(points[idx])

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

Kth Largest Element in an Array

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Can you solve it without sorting?

A
import heapq
min_heap = []
result = 0

for idx, num in enumerate(nums):
    heapq.heappush(min_heap, num)
		if len(min_heap) > k:
		    heapq.heappop(min_heap)

return heapq.heappop(min_heap)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Top K Frequent Elements

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

A
import heapq

min_heap = []
hash_map = {}
result = []

for num in nums:
    if num not in hash_map:
        hash_map[num] = 1
		else:
		    hash_map[num] += 1
for key in hash_map:
    heapq.heappush(min_heap, (hash_map[key], key))
		if len(min_heap) > k:
		    heapq.heappop(min_heap)
for _, num in min_heap:
    result.append(num)
		
return result
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Sort Characters By Frequency

Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.

Return the sorted string. If there are multiple answers, return any of them.

A
hash_map = {}

for char in s:
    if char in hash_map:
        hash_map[char] += 1
    else:
		    hash_map[char] = 1

return ''.join(sorted(s, key = lambda x: (-hash_map[x], x)))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Maximum Ice Cream Bars

It is a sweltering summer day, and a boy wants to buy some ice cream bars.

At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible.

Note: The boy can buy the ice cream bars in any order.

Return the maximum number of ice cream bars the boy can buy with coins coins.

You must solve the problem by counting sort.

A
counter = 0
sorted_arr = self.counting_sort(costs)
for num in sorted_arr:
    if num > coins:
		    return counter
    else:
		    coins -= num
	      counter += 1
return counter
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Counting Sort (Algorithm)

A
if not nums:
    return []

max_elem = max(nums)
count = [0] * max_elem+1
for num in nums:
    count[num] += 1
for i in range(1, len(count)):
    count[i] += count[i-1]
sorted_arr = [0] * len(nums)
for num in nums:
    sorted_arr[count[num]-1] = num
    count -= 1
return sorted_arr
17
Q

Custom Sort String

You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.

Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.

Return any permutation of s that satisfies this property.

A
hash_map = {}
result = ""
for char in order:
    hash_map[char] = 0

for char in s:
    if char in hash_map:
        hash_map[char] += 1
    else:
		    hash_map[char] = 1

for key in hash_map:
    occurances = hash_map[key]
    for i in range(occurances):
		    result += key

return result
		
18
Q

Relative Sort Array

Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.

Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order.

A
hash_map = {}
temp_arr = []
result =[]
for num in arr2:
    hash_map[num] = 0
for num in arr1: 
    if num in hash_map:
		    hash_map[num] += 1
		else:
		    temp_arr.append(num)
temp_arr = self.counting_sort(temp_arr)

for key in hash_map:
    occurances = hash_map[key]
    for i in range(occurances):
        result.append(key)

for num in temp_arr:
    result.append(num)

return result