The-Grand-Complete-Data-Science-Materials: Krishnaik06
The-Grand-Complete-Data-Science-Materials: Krishnaik06
The-Grand-Complete-Data-Science-Materials / Python / Python DSA Interviews.md Question: Generate the nth Fibonacci number.
Answer:
krishnaik06 Add files via upload 3 weeks ago
def fibonacci(n):
1500 lines (1105 loc) · 63.7 KB if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
Preview Code Blame Raw
Here's a comprehensive list of interview questions on data structures and algorithms, along 5. Linked List Cycle Detection
with their answers and Python code:
Question: Detect if there is a cycle in a linked list.
1. Reverse a String Answer:
def is_palindrome(s):
return s == s[::-1]
6. Merge Two Sorted Lists
import heapq
class Stack:
def __init__(self):
class PriorityQueue:
self.top = None
def __init__(self):
self.queue = []
def push(self, value):
self.top = StackNode(value, self.top)
def enqueue(self, value, priority=0):
heapq.heappush(self.queue, (priority, value))
def pop(self):
if not self.top:
def dequeue(self):
return None
return heapq.heappop(self.queue)[1] if self.queue else None
value = self.top.value
self.top = self.top.next
return value
class Hashmap:
def __init__(self):
13. Implement a Queue self.size = 1000
self.map = [None] * self.size
Question: Implement a queue using two stacks.
def _hash(self, key):
Answer: return hash(key) % self.size
while queue:
vertex = queue.popleft() 22. Implement MergeSort
order.append(vertex)
for neighbor in graph[vertex]: Question: Implement the mergesort algorithm.
in_degree[neighbor] -= 1 Answer:
if in_degree[neighbor] == 0:
queue.append(neighbor)
def mergesort(arr):
return order if len(order) == len(vertices) else [] if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = arr[:mid]
20. Check if a String Contains All Binary Codes of Size K right = arr[mid:]
return merge(mergesort(left), mergesort(right))
Question: Given a binary string s and an integer k , check if all binary codes of length
k is a substring of s . def merge(left, right):
result = []
Answer:
i = j = 0
while i < len(left) and j < len(right):
def has_all_codes(s, k): if left[i] < right[j]:
needed = 1 << k result.append(left[i])
seen = set() i += 1
else:
for i in range(len(s) - k + 1): result.append(right[j])
substring = s[i:i+k] j += 1
if substring not in seen: result.extend(left[i:])
seen.add(substring) result.extend(right[j:])
needed -= 1 return result
if needed == 0:
return True
return False
23. Maximum Depth of Binary Tree
left_max[0] = height[0]
for i in range(1, n):
24. Count the Number of Islands left_max[i] = max(height[i], left_max[i-1])
Question: Given a 2D grid consisting of '1's (land) and '0's (water), count the number of right_max[n-1] = height[n-1]
islands. An island is surrounded by water and is formed by connecting adjacent lands for i in range(n-2, -1, -1):
horizontally or vertically. right_max[i] = max(height[i], right_max[i+1])
Answer: ans = 0
for i in range(n):
ans += min(left_max[i], right_max[i]) - height[i]
def num_islands(grid):
if not grid:
return ans
return 0
count = 0
for i in range(len(grid)):
26. Coin Change
for j in range(len(grid[0])):
if grid[i][j] == '1':
Question: You are given coins of different denominations and a total amount of money
dfs(grid, i, j)
count += 1 amount. Write a function to compute the fewest number of coins that you need to make
return count up that amount. If that amount of money cannot be made up by any combination of the
coins, return -1.
def dfs(grid, i, j):
Answer:
if (i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] !=
'1'):
return def coin_change(coins, amount):
grid[i][j] = '#' dp = [float('inf')] * (amount + 1)
dfs(grid, i-1, j) dp[0] = 0
dfs(grid, i+1, j)
dfs(grid, i, j-1) for coin in coins:
dfs(grid, i, j+1) for x in range(coin, amount + 1):
dp[x] = min(dp[x], dp[x - coin] + 1)
Question: Given n non-negative integers representing an elevation map where the width 27. Decode Ways
of each bar is 1, compute how much water it can trap after raining.
Question: A message containing letters from A-Z is being encoded to numbers using the
Answer:
following mapping: 'A' -> '1', 'B' -> '2', ..., 'Z' -> '26'. Given a non-empty string containing
only digits, determine the total number of ways to decode it.
def trap(height):
if not height: Answer:
return 0
def num_decodings(s):
n = len(height)
if not s:
left_max = [0] * n
return 0
n = len(s) def fibonacci(n):
dp = [0] * (n + 1) if n <= 1:
dp[0] = 1 return n
dp[1] = 0 if s[0] == '0' else 1 a, b = 0, 1
for _ in range(2, n + 1):
for i in range(2, n + 1): a, b = b, a + b
first = int(s[i-1:i]) return b
second = int(s[i-2:i])
if 1 <= first <= 9:
dp[i] += dp[i-1]
if 10 <= second <= 26:
30. Longest Increasing Subsequence
dp[i] += dp[i-2]
Question: Given an unsorted array of integers, find the length of longest increasing
return dp[n] subsequence.
Answer:
def max_area(height):
return max(dp)
left, right = 0, len(height) - 1
max_area = 0
Question: Implement a function to compute the nth Fibonacci number. Question: Given an integer array nums, find the contiguous subarray (containing at least
Answer: one number) which has the largest sum and return its sum.
Answer:
def max_sub_array(nums): return not stack
if not nums:
return 0
cur_sum = max_sum = nums[0]
for num in nums[1:]: 35. Reverse a String
cur_sum = max(num, cur_sum + num)
max_sum = max(max_sum, cur_sum) Question: Implement a function that reverses a string.
return max_sum
Answer:
def reverse_string(s):
33. Longest Common Prefix return s[::-1]
Question: Write a function to find the longest common prefix string amongst an array of
strings. If there is no common prefix, return an empty string "".
36. Intersection of Two Arrays II
Answer:
Question: Given two arrays, write a function to compute their intersection. Each element
def longest_common_prefix(strs): in the result should appear as many times as it shows in both arrays. The result can be in
if not strs: any order.
return ""
Answer:
prefix = strs[0]
for s in strs[1:]: from collections import Counter
i = 0
while i < len(prefix) and i < len(s) and prefix[i] == s[i]:
def intersect(nums1, nums2):
i += 1 c1, c2 = Counter(nums1), Counter(nums2)
prefix = prefix[:i] return list((c1 & c2).elements())
return prefix
def single_number(nums):
def is_valid(s): res = 0
stack = []
for num in nums:
mapping = {")": "(", "}": "{", "]": "["}
res ^= num
return res
for char in s:
if char in mapping:
top_element = stack.pop() if stack else '#'
if mapping[char] != top_element: 38. Rotate Array
return False
else: Question: Given an array, rotate the array to the right by k steps, where k is non-negative.
stack.append(char)
Answer:
from collections import Counter
Question: Given an array nums of n integers where n > 1, return an array output such
that output[i] is equal to the product of all the elements of nums except nums[i]. 42. Two Sum
Answer: Question: Given an array of integers nums and an integer target , return indices of the
two numbers such that they add up to target .
def product_except_self(nums): Answer:
length = len(nums)
output = [1] * length
left, right = 1, 1 def two_sum(nums, target):
num_to_index = {}
for i in range(length): for i, num in enumerate(nums):
output[i] *= left diff = target - num
left *= nums[i] if diff in num_to_index:
output[-1 - i] *= right return [num_to_index[diff], i]
right *= nums[-1 - i] num_to_index[num] = i
return output
40. Implement strStr() Question: Count the number of prime numbers less than a non-negative number, n.
Answer:
Question: Implement strStr() . Return the index of the first occurrence of needle in
haystack, or -1 if needle is not part of haystack.
def count_primes(n):
Answer:
if n <= 2:
return 0
def str_str(haystack, needle): primes = [True] * n
if not needle: primes[0], primes[1] = False, False
return 0 for i in range(2, int(n**0.5) + 1):
return haystack.find(needle) if primes[i]:
for j in range(i*i, n, i):
primes[j] = False
return sum(primes)
41. First Unique Character in a String
Question: Given a string, find the first non-repeating character in it and return its index. If
44. Majority Element
it doesn't exist, return -1 .
Answer:
Question: Given an array of size n, find the majority element. The majority element is the return True
def move_zeroes(nums):
pos = 0
45. Valid Sudoku for i in range(len(nums)):
if nums[i] != 0:
Question: Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be nums[pos], nums[i] = nums[i], nums[pos]
pos += 1
validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
47. Best Time to Buy and Sell Stock
Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.
Answer: Question: Say you have an array for which the i th element is the price of a given stock
on day i . If you were only permitted to complete at most one transaction (i.e., buy one
and sell one share of the stock), design an algorithm to find the maximum profit.
def is_valid_sudoku(board):
rows = [set() for _ in range(9)] Answer:
cols = [set() for _ in range(9)]
boxes = [set() for _ in range(9)]
def max_profit(prices):
if not prices:
for i in range(9):
return 0
for j in range(9):
val = board[i][j]
min_price = prices[0]
if val == '.':
max_profit = 0
continue
box_idx = (i // 3) * 3 + j // 3
if val in boxes[box_idx]:
48. Valid Anagram
return False
boxes[box_idx].add(val)
Question: Given two strings s and t , write a function to determine if t is an anagram
of s .
Answer:
These are just some examples, and the above solutions can be optimized and extended in
from collections import Counter
various ways, depending on the exact constraints and requirements.
def is_anagram(s, t):
return Counter(s) == Counter(t)
51. Merge Two Sorted Lists
Question: Merge two sorted linked lists and return it as a new sorted list.
Answer:
49. Maximum Depth of Binary Tree
Question: Given a binary tree, find its maximum depth. The maximum depth is the class ListNode:
def __init__(self, val=0, next=None):
number of nodes along the longest path from the root node down to the farthest leaf
self.val = val
node.
self.next = next
Answer:
def merge_two_lists(l1, l2):
dummy = ListNode(-1)
class TreeNode:
prev = dummy
def __init__(self, val=0, left=None, right=None):
self.val = val
while l1 and l2:
self.left = left
if l1.val <= l2.val:
self.right = right
prev.next = l1
l1 = l1.next
def max_depth(root):
else:
if not root:
prev.next = l2
return 0
l2 = l2.next
return 1 + max(max_depth(root.left), max_depth(root.right))
prev = prev.next
prev.next = l1 if l1 else l2
return dummy.next
50. Palindrome Linked List
def is_palindrome(head):
class MyStack:
vals = []
def __init__(self):
current = head
self.q = deque()
while current:
vals.append(current.val)
def push(self, x):
current = current.next
self.q.append(x)
return vals == vals[::-1]
for _ in range(len(self.q) - 1):
self.q.append(self.q.popleft())
def pop(self):
return self.q.popleft() def level_order(root):
if not root:
def top(self): return []
return self.q[0] result, queue = [], [root]
while queue:
def empty(self): level, level_len = [], len(queue)
return not self.q for i in range(level_len):
node = queue.pop(0)
level.append(node.val)
if node.left:
53. Min Stack queue.append(node.left)
if node.right:
Question: Design a stack that supports push, pop, top, and retrieving the minimum queue.append(node.right)
element in constant time. result.append(level)
return result
Answer:
class MinStack:
def __init__(self): 55. Linked List Cycle
self.stack = []
self.min_stack = [] Question: Given a linked list, determine if it has a cycle in it.
Answer:
def push(self, x):
self.stack.append(x)
if not self.min_stack or x <= self.min_stack[-1]: class ListNode:
self.min_stack.append(x) def __init__(self, x):
self.val = x
def pop(self): self.next = None
if self.stack.pop() == self.min_stack[-1]:
self.min_stack.pop() def has_cycle(head):
slow, fast = head, head
def top(self): while fast and fast.next:
return self.stack[-1] slow = slow.next
fast = fast.next.next
def getMin(self): if slow == fast:
return self.min_stack[-1] return True
return False
class TreeNode:
def __init__(self, val=0, left=None, right=None): class TreeNode:
self.val = val def __init__(self, val=0, left=None, right=None):
self.left = left self.val = val
self.right = right self.left = left
self.right = right
def invert_tree(root): def top_k_frequent(nums, k):
if not root: count = Counter(nums)
return None return heapq.nlargest(k, count.keys(), key=count.get)
root.left, root.right = invert_tree(root.right), invert_tree(root.left)
return root
57. Serialize and Deserialize Binary Tree Question: Given an encoded string, return its decoded string. The encoding rule is:
k[encoded_string], where the encoded_string inside the square brackets is being
Question: Design an algorithm to serialize and deserialize a binary tree.
repeated exactly k times.
Answer:
Answer:
class TreeNode:
def decode_string(s):
def __init__(self, x):
stack, curr_num, curr_str = [], 0, ''
self.val = x
for char in s:
self.left = None
if char == '[':
self.right = None
stack.append(curr_str)
stack.append(curr_num)
class Codec:
curr_str, curr_num = '', 0
def serialize(self, root):
elif char == ']':
def dfs(node):
num = stack.pop()
if not node:
prev_str = stack.pop()
return ["None"]
curr_str = prev_str + num * curr_str
return [str(node.val)] + dfs(node.left) + dfs(node.right)
elif char.isdigit():
return ",".join(dfs(root))
curr_num = curr_num * 10 + int(char)
else:
def deserialize(self, data):
curr_str += char
data_list = data.split(',')
return curr_str
def dfs():
val = data_list.pop(0)
if val == "None":
return None 60. Number of Islands
node = TreeNode(int(val))
node.left = dfs() Question: Given a 2D grid map of '1's (land) and '0's (water), count the number of islands.
node.right = dfs()
return node Answer:
return dfs()
def num_islands(grid):
if not grid:
return 0
58. Top K Frequent Elements
rows, cols = len(grid), len(grid[0])
Question: Given a non-empty array of integers, return the k most frequent elements.
visited = [[0 for _ in range(cols)] for _ in range(rows)]
Answer: directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
islands = 0
return islands Question: Given an image represented by an NxN matrix, rotate the image by 90
degrees.
Answer:
The explanations have been excluded for brevity, but it's essential to understand the logic
behind each code snippet and be prepared to explain the solution's approach and its time def rotate(matrix):
n = len(matrix)
and space complexity.
for i in range(n):
for j in range(i, n):
61. Maximum Depth of Binary Tree
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for row in matrix:
Question: Given a binary tree, find its maximum depth.
row.reverse()
Answer:
class TreeNode:
64. Palindrome Linked List
def __init__(self, val=0, left=None, right=None):
self.val = val
Question: Check if a singly linked list is a palindrome.
self.left = left
self.right = right Answer:
def max_depth(root):
class ListNode:
if not root:
def __init__(self, val=0, next=None):
return 0
self.val = val
left = max_depth(root.left)
self.next = next
right = max_depth(root.right)
return max(left, right) + 1
def is_palindrome(head):
values = []
current = head
while current:
62. Two Sum
values.append(current.val)
current = current.next
Question: Given an array of integers, return indices of the two numbers such that they
return values == values[::-1]
add up to a specific target.
Answer:
for i in range(n - 2, -1, -1): Question: Given a list of non-negative integers representing the amount of money of
right[i] = nums[i + 1] * right[i + 1]
each house, determine the maximum amount of money you can rob without alerting the
for i in range(n):
police (you cannot rob two adjacent houses).
output[i] = left[i] * right[i] Answer:
return output
def rob(nums):
if not nums:
return 0
66. Find All Duplicates in an Array if len(nums) == 1:
return nums[0]
Question: Given an array of integers, where 1 ≤ a[i] ≤ n (n = size of array), some elements prev = nums[0]
curr = max(nums[0], nums[1])
appear twice and others appear once. Find all the elements that appear twice.
for i in range(2, len(nums)):
Answer: temp = curr
curr = max(prev + nums[i], curr)
prev = temp
def find_duplicates(nums):
return curr
result = []
for num in nums:
index = abs(num) - 1
if nums[index] < 0:
69. Longest Palindromic Substring
result.append(index + 1)
nums[index] = -nums[index]
Question: Given a string, find the longest substring which is a palindrome.
return result
Answer:
def longest_palindrome(s):
67. Coin Change
if not s:
return ""
Question: You are given coins of different denominations and a total amount of money
amount. Write a function to compute the fewest number of coins that you need to make
def expand_center(left, right):
up that amount. If that amount of money cannot be made up by any combination of the while left >= 0 and right < len(s) and s[left] == s[right]:
coins, return -1 . left -= 1
right += 1
Answer:
return s[left + 1:right]
result = ""
for i in range(len(s)): return True
# Odd length palindrome
palindrome1 = expand_center(i, i)
# Even length palindrome
palindrome2 = expand_center(i, i + 1) These solutions are just the code implementations. It's important to understand the logic,
approach, and potentially the time and space complexities behind each one.
if len(palindrome1) > len(result):
result = palindrome1
if len(palindrome2) > len(result):
result = palindrome2
return result
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()