? Python Data Science Interview Questions
? Python Data Science Interview Questions
Here's a comprehensive list of interview questions on data structures and algorithms, along
with their answers and Python code:
1. Reverse a String
def reverse_string(s):
return s[::-1]
2. Check Palindrome
def is_palindrome(s):
return s == s[::-1]
3. Find Factorial
4. Fibonacci Series
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
def has_cycle(node):
slow, fast = node, node
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
current.next = l1 or l2
return dummy.next
def find_middle(node):
slow, fast = node, node
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
def max_subarray(nums):
max_current = max_global = nums[0]
for i in range(1, len(nums)):
max_current = max(nums[i], max_current + nums[i])
max_global = max(max_global, max_current)
return max_global
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def is_balanced(root):
def check_balance(node):
if not node:
return 0, True
left_height, left_balanced = check_balance(node.left)
right_height, right_balanced = check_balance(node.right)
return max(left_height, right_height) + 1, left_balanced and
right_balanced and abs(left_height - right_height) <= 1
return check_balance(root)[1]
class StackNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
class Stack:
def __init__(self):
self.top = None
def pop(self):
if not self.top:
return None
value = self.top.value
self.top = self.top.next
return value
def peek(self):
return None if not self.top else self.top.value
def is_empty(self):
return self.top is None
class Queue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def dequeue(self):
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop() if self.stack2 else None
import heapq
class PriorityQueue:
def __init__(self):
self.queue = []
def dequeue(self):
return heapq.heappop(self.queue)[1] if self.queue else None
class Hashmap:
def __init__(self):
self.size = 1000
self.map = [None] * self.size
Question: Implement a basic trie for word insert, search and prefix search.
Answer:
class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
Question: Given a sorted array of integers and a target value, find the starting and
ending position of the target value using binary search.
Answer:
for u, v in edges:
graph[u].append(v)
in_degree[v] += 1
while queue:
vertex = queue.popleft()
order.append(vertex)
for neighbor in graph[vertex]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)
Question: Given a binary string s and an integer k , check if all binary codes of
length k is a substring of s .
Answer:
return False
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
def mergesort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
return merge(mergesort(left), mergesort(right))
def max_depth(root):
if not root:
return 0
left_depth = max_depth(root.left)
right_depth = max_depth(root.right)
return max(left_depth, right_depth) + 1
Question: Given a 2D grid consisting of '1's (land) and '0's (water), count the number
of islands. An island is surrounded by water and is formed by connecting adjacent
lands horizontally or vertically.
Answer:
def num_islands(grid):
if not grid:
return 0
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
dfs(grid, i, j)
count += 1
return count
def trap(height):
if not height:
return 0
n = len(height)
left_max = [0] * n
right_max = [0] * n
left_max[0] = height[0]
for i in range(1, n):
left_max[i] = max(height[i], left_max[i-1])
right_max[n-1] = height[n-1]
for i in range(n-2, -1, -1):
right_max[i] = max(height[i], right_max[i+1])
ans = 0
for i in range(n):
ans += min(left_max[i], right_max[i]) - height[i]
return ans
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 up that amount. If that amount of money cannot be made up by any
combination of the coins, return -1.
Answer:
Question: A message containing letters from A-Z is being encoded to numbers using
the 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.
Answer:
def num_decodings(s):
if not s:
return 0
n = len(s)
dp = [0] * (n + 1)
dp[0] = 1
dp[1] = 0 if s[0] == '0' else 1
return dp[n]
Question: Given n non-negative integers a1, a2, ..., an , where each represents a
point at coordinate (i, ai) . n vertical lines are drawn such that the two endpoints of
the line i is at (i, ai) and (i, 0) . Find two lines, which, together with the x-axis
forms a container, such that the container contains the most water.
Answer:
def max_area(height):
left, right = 0, len(height) - 1
max_area = 0
return max_area
def fibonacci(n):
if n <= 1:
return n
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return b
Question: Given an unsorted array of integers, find the length of longest increasing
subsequence.
Answer:
def length_of_lis(nums):
if not nums:
return 0
dp = [1] * len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
Question: Write a function that checks whether a given word or phrase is palindrome.
Answer:
def is_palindrome(s):
s = ''.join([c for c in s if c.isalnum()]).lower()
return s == s[::-1]
Question: Given an integer array nums, find the contiguous subarray (containing at
least one number) which has the largest sum and return its sum.
Answer:
def max_sub_array(nums):
if not nums:
return 0
cur_sum = max_sum = nums[0]
for num in nums[1:]:
cur_sum = max(num, cur_sum + num)
max_sum = max(max_sum, cur_sum)
return max_sum
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 "".
Answer:
def longest_common_prefix(strs):
if not strs:
return ""
prefix = strs[0]
for s in strs[1:]:
i = 0
while i < len(prefix) and i < len(s) and prefix[i] == s[i]:
i += 1
prefix = prefix[:i]
return prefix
Question: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine
if the input string is valid. An input string is valid if brackets are closed in the correct
order.
Answer:
def is_valid(s):
stack = []
mapping = {")": "(", "}": "{", "]": "["}
for char in s:
if char in mapping:
top_element = stack.pop() if stack else '#'
if mapping[char] != top_element:
return False
else:
stack.append(char)
def reverse_string(s):
return s[::-1]
Question: Given two arrays, write a function to compute their intersection. Each
element in the result should appear as many times as it shows in both arrays. The
result can be in any order.
Answer:
from collections import Counter
Question: Given a non-empty array of integers nums, every element appears twice
except for one. Find that single one.
Answer:
def single_number(nums):
res = 0
for num in nums:
res ^= num
return res
Question: Given an array, rotate the array to the right by k steps, where k is non-
negative.
Answer:
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].
Answer:
def product_except_self(nums):
length = len(nums)
output = [1] * length
left, right = 1, 1
for i in range(length):
output[i] *= left
left *= nums[i]
output[-1 - i] *= right
right *= nums[-1 - i]
return output
Question: Implement strStr() . Return the index of the first occurrence of needle in
haystack, or -1 if needle is not part of haystack.
Answer:
Question: Given a string, find the first non-repeating character in it and return its
index. If it doesn't exist, return -1 .
Answer:
def first_uniq_char(s):
count = Counter(s)
for idx, ch in enumerate(s):
if count[ch] == 1:
return idx
return -1
Question: Given an array of integers nums and an integer target , return indices of
the two numbers such that they add up to target .
Answer:
def two_sum(nums, target):
num_to_index = {}
for i, num in enumerate(nums):
diff = target - num
if diff in num_to_index:
return [num_to_index[diff], i]
num_to_index[num] = i
Question: Count the number of prime numbers less than a non-negative number, n.
Answer:
def count_primes(n):
if n <= 2:
return 0
primes = [True] * n
primes[0], primes[1] = False, False
for i in range(2, int(n**0.5) + 1):
if primes[i]:
for j in range(i*i, n, i):
primes[j] = False
return sum(primes)
Question: Given an array of size n, find the majority element. The majority element is
the element that appears more than n/2 times.
Answer:
def majority_element(nums):
counts = Counter(nums)
return max(counts.keys(), key=counts.get)
Question: Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be
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.
Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without
repetition.
Answer:
def is_valid_sudoku(board):
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
boxes = [set() for _ in range(9)]
for i in range(9):
for j in range(9):
val = board[i][j]
if val == '.':
continue
if val in rows[i]:
return False
rows[i].add(val)
if val in cols[j]:
return False
cols[j].add(val)
box_idx = (i // 3) * 3 + j // 3
if val in boxes[box_idx]:
return False
boxes[box_idx].add(val)
return True
Question: Given an array nums , write a function to move all 0 's to the end of it while
maintaining the relative order of the non-zero elements.
Answer:
def move_zeroes(nums):
pos = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[pos], nums[i] = nums[i], nums[pos]
pos += 1
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.
Answer:
def max_profit(prices):
if not prices:
return 0
min_price = prices[0]
max_profit = 0
return max_profit
Question: Given a binary tree, find its maximum depth. The maximum depth is the
number of nodes along the longest path from the root node down to the farthest leaf
node.
Answer:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def max_depth(root):
if not root:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def is_palindrome(head):
vals = []
current = head
while current:
vals.append(current.val)
current = current.next
return vals == vals[::-1]
These are just some examples, and the above solutions can be optimized and extended in
various ways, depending on the exact constraints and requirements.
Question: Merge two sorted linked lists and return it as a new sorted list.
Answer:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
prev.next = l1 if l1 else l2
return dummy.next
class MyStack:
def __init__(self):
self.q = deque()
def pop(self):
return self.q.popleft()
def top(self):
return self.q[0]
def empty(self):
return not self.q
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = []
def pop(self):
if self.stack.pop() == self.min_stack[-1]:
self.min_stack.pop()
def top(self):
return self.stack[-1]
def getMin(self):
return self.min_stack[-1]
Question: Given a binary tree, return the level order traversal of its nodes' values.
Answer:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def level_order(root):
if not root:
return []
result, queue = [], [root]
while queue:
level, level_len = [], len(queue)
for i in range(level_len):
node = queue.pop(0)
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level)
return result
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def has_cycle(head):
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def invert_tree(root):
if not root:
return None
root.left, root.right = invert_tree(root.right), invert_tree(root.left)
return root
57. Serialize and Deserialize Binary Tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
def dfs(node):
if not node:
return ["None"]
return [str(node.val)] + dfs(node.left) + dfs(node.right)
return ",".join(dfs(root))
Question: Given a non-empty array of integers, return the k most frequent elements.
Answer:
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
repeated exactly k times.
Answer:
def decode_string(s):
stack, curr_num, curr_str = [], 0, ''
for char in s:
if char == '[':
stack.append(curr_str)
stack.append(curr_num)
curr_str, curr_num = '', 0
elif char == ']':
num = stack.pop()
prev_str = stack.pop()
curr_str = prev_str + num * curr_str
elif char.isdigit():
curr_num = curr_num * 10 + int(char)
else:
curr_str += char
return curr_str
Question: Given a 2D grid map of '1's (land) and '0's (water), count the number of
islands.
Answer:
def num_islands(grid):
if not grid:
return 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == '1' and not visited[r][c]:
dfs(r, c)
islands += 1
return islands
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
and space complexity.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def max_depth(root):
if not root:
return 0
left = max_depth(root.left)
right = max_depth(root.right)
return max(left, right) + 1
Question: Given an array of integers, return indices of the two numbers such that they
add up to a specific target.
Answer:
def rotate(matrix):
n = len(matrix)
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for row in matrix:
row.reverse()
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def is_palindrome(head):
values = []
current = head
while current:
values.append(current.val)
current = current.next
return values == values[::-1]
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].
Answer:
def product_except_self(nums):
n = len(nums)
left, right, output = [1] * n, [1] * n, [1] * n
for i in range(n):
output[i] = left[i] * right[i]
return output
def find_duplicates(nums):
result = []
for num in nums:
index = abs(num) - 1
if nums[index] < 0:
result.append(index + 1)
nums[index] = -nums[index]
return result
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 up that amount. If that amount of money cannot be made up by any
combination of the coins, return -1 .
Answer:
def rob(nums):
if not nums:
return 0
if len(nums) == 1:
return nums[0]
prev = nums[0]
curr = max(nums[0], nums[1])
for i in range(2, len(nums)):
temp = curr
curr = max(prev + nums[i], curr)
prev = temp
return curr
def longest_palindrome(s):
if not s:
return ""
result = ""
for i in range(len(s)):
# Odd length palindrome
palindrome1 = expand_center(i, i)
# Even length palindrome
palindrome2 = expand_center(i, i + 1)
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
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.