Python Interview Questions - Arrays & Strings (Solutions Only)
Two Sum
def twoSum(nums, target):
hashmap = {}
for i, num in enumerate(nums):
if target - num in hashmap:
return [hashmap[target - num], i]
hashmap[num] = i
3Sum
def threeSum(nums):
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
Container With Most Water
def maxArea(height):
l, r, res = 0, len(height) - 1, 0
while l < r:
res = max(res, min(height[l], height[r]) * (r - l))
if height[l] < height[r]: l += 1
else: r -= 1
return res
Longest Substring Without Repeating Characters
def lengthOfLongestSubstring(s):
char_set = set()
l = res = 0
for r in range(len(s)):
while s[r] in char_set:
char_set.remove(s[l])
l += 1
char_set.add(s[r])
res = max(res, r - l + 1)
return res
Longest Palindromic Substring
def longestPalindrome(s):
res = ""
for i in range(len(s)):
for a, b in [(i, i), (i, i+1)]:
while a >= 0 and b < len(s) and s[a] == s[b]:
a -= 1; b += 1
res = max(res, s[a+1:b], key=len)
return res
Group Anagrams
from collections import defaultdict
def groupAnagrams(strs):
res = defaultdict(list)
for s in strs:
key = tuple(sorted(s))
res[key].append(s)
return list(res.values())
Multiply Strings
def multiply(num1, num2):
return str(int(num1) * int(num2))
Minimum Window Substring
from collections import Counter
def minWindow(s, t):
if not t or not s: return ""
t_count = Counter(t)
window_count = {}
have = need = len(t_count)
l = res = 0, float("inf")
count = 0
for r, c in enumerate(s):
window_count[c] = window_count.get(c, 0) + 1
if c in t_count and window_count[c] == t_count[c]:
count += 1
while count == need:
if (r - l + 1) < (res[1] - res[0]):
res = (l, r + 1)
window_count[s[l]] -= 1
if s[l] in t_count and window_count[s[l]] < t_count[s[l]]:
count -= 1
l += 1
return s[res[0]:res[1]] if res[1] != float("inf") else
String to Integer (atoi)
def myAtoi(s):
s = s.strip()
if not s: return 0
sign, i, res = 1, 0, 0
if s[0] in "+-":
sign = -1 if s[0] == '-' else 1
i += 1
while i < len(s) and s[i].isdigit():
res = res * 10 + int(s[i])
i += 1
res *= sign
return max(min(res, 2**31 - 1), -2**31)
Valid Parentheses
def isValid(s):
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for c in s:
if c in mapping:
top = stack.pop() if stack else '#'
if mapping[c] != top:
return False
else:
stack.append(c)
return not stack
Decode String
def decodeString(s):
stack = []
curr_str = ''
curr_num = 0
for c in s:
if c == '[':
stack.append((curr_str, curr_num))
curr_str, curr_num = '', 0
elif c == ']':
last_str, num = stack.pop()
curr_str = last_str + num * curr_str
elif c.isdigit():
curr_num = curr_num * 10 + int(c)
else:
curr_str += c
return curr_str
Longest Common Prefix
def longestCommonPrefix(strs):
if not strs: return ""
prefix = strs[0]
for s in strs[1:]:
while s.find(prefix) != 0:
prefix = prefix[:-1]
if not prefix:
return ""
return prefix
Word Search
def exist(board, word):
rows, cols = len(board), len(board[0])
def backtrack(r, c, i):
if i == len(word): return True
if r < 0 or c < 0 or r >= rows or c >= cols or board[r][c] != word[i]:
return False
tmp, board[r][c] = board[r][c], '#'
found = any(backtrack(r+dr, c+dc, i+1) for dr, dc in ((1,0), (-1,0), (0,1), (0,-1)))
board[r][c] = tmp
return found
return any(backtrack(r, c, 0) for r in range(rows) for c in range(cols))
Letter Combinations of a Phone Number
def letterCombinations(digits):
if not digits: return []
phone = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv",
"9": "wxyz"}
res = ['']
for d in digits:
res = [prefix + c for prefix in res for c in phone[d]]
return res
Count and Say
def countAndSay(n):
res = "1"
for _ in range(n - 1):
curr, count, temp = res[0], 1, ""
for i in range(1, len(res)):
if res[i] == curr:
count += 1
else:
temp += str(count) + curr
curr, count = res[i], 1
temp += str(count) + curr
res = temp
return res