Python Ussecases Interview Based Questions: The-Grand-Complete-Data-Science-Materials
Python Ussecases Interview Based Questions: The-Grand-Complete-Data-Science-Materials
if n == 0:
return 1
Code Issues Pull requests 4 Actions Projects Security Insights return n * factorial(n-1)
number = 5
The-Grand-Complete-Data-Science-Materials / Python / Python Interview Usecases.md print(factorial(number)) # Output: 120
Answer: A palindrome is a word, phrase, number, or other sequences of characters that reads
the same forward and backward (ignoring spaces, punctuation, and capitalization).
Python Ussecases Interview Based Questions
def is_palindrome(s):
Below are some use-case based Python interview questions along with their answers and s = ''.join(e for e in s if e.isalnum()) # Remove punctuation and spaces
code. return s.lower() == s.lower()[::-1]
def filter_palindromes(strings):
return [s for s in strings if is_palindrome(s)]
1. Question: Given a list of numbers, write a Python function to find the second highest
words = ["radar", "python", "level", "world"]
number.
print(filter_palindromes(words)) # Output: ['radar', 'level']
Answer: We can first convert the list into a set to remove duplicates. Then, we'll convert it
back to a list and sort it. We can retrieve the second last element to get the second highest
number.
str1 = "listen"
str2 = "silent"
print(are_anagrams(str1, str2)) # Output: True
Answer:
Remember, these solutions can be optimized or presented in different ways depending on the
context and requirements of the interview.
9. Question: Write a function that finds the most repeated character in a string.
6. Question: Given two lists, write a function that returns the elements that are common to Answer:
both lists.
string = "aabbbcdddde"
print(most_repeated(string)) # Output: 'd'
Answer:
10. Question: Write a function that checks if a string contains all letters of the alphabet at
least once.
def word_count(s):
return len(s.split())
Answer:
sentence = "The quick brown fox"
print(word_count(sentence)) # Output: 4 import string
def contains_all_alphabets(s):
alphabet = set(string.ascii_lowercase) 5}
return set(s.lower()) >= alphabet
test_string = "The quick brown fox jumps over the lazy dog"
print(contains_all_alphabets(test_string)) # Output: True
Answer:
11. Question: Write a function that checks if a given string is a valid IPv4 address.
def fibonacci(n):
series = [0, 1]
Answer:
while len(series) < n:
series.append(series[-1] + series[-2])
def is_valid_ipv4(ip): return series
parts = ip.split(".")
if len(parts) != 4: number = 10
return False print(fibonacci(number)) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
for item in parts:
if not item.isdigit():
return False
num = int(item)
if num < 0 or num > 255:
return False
14. Question: Given a string, write a function that returns the first non-repeated character.
return True
Answer:
address = "192.168.1.1"
print(is_valid_ipv4(address)) # Output: True
def first_non_repeated(s):
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
12. Question: Given a list of numbers, write a function to compute the mean, median, and
char_count[char] = 1
mode.
for char in s:
if char_count[char] == 1:
Answer: return char
return None
from statistics import mean, median, mode
string = "swiss"
def compute_stats(numbers): print(first_non_repeated(string)) # Output: 'w'
return {
"mean": mean(numbers),
"median": median(numbers),
"mode": mode(numbers)
}
15. Question: Write a function to check if two strings are a rotation of each other (e.g.,
numbers = [1, 2, 3, 4, 4, 5, 5, 5, 6]
"abcde" and "cdeab" are rotations of each other).
print(compute_stats(numbers)) # Output: {'mean': 3.89, 'median': 4, 'mode':
Answer:
current_streak
def are_rotations(str1, str2):
if len(str1) != len(str2): numbers = [1, 2, 3, 5, 6, 7, 8, 10]
return False print(longest_consecutive_subsequence(numbers)) # Output: [5, 6, 7, 8]
return str1 in str2 + str2
s1 = "abcde"
s2 = "cdeab"
print(are_rotations(s1, s2)) # Output: True
18. Question: Write a function to compute the square root of a given non-negative integer n
without using built-in square root functions or libraries. Return the floor value of the result.
Answer:
16. Question: Write a function to determine if a string has all unique characters (i.e., no
character is repeated). def sqrt(n):
if n < 0:
Answer: return None
if n == 1:
return 1
def has_unique_chars(s): start, end = 0, n
return len(s) == len(set(s)) while start <= end:
mid = (start + end) // 2
string = "abcdef" if mid * mid == n:
print(has_unique_chars(string)) # Output: True return mid
elif mid * mid < n:
start = mid + 1
ans = mid
else:
end = mid - 1
17. Question: Write a function that returns the longest consecutive subsequence in a list of
return ans
numbers.
number = 17
Answer: print(sqrt(number)) # Output: 4
def longest_consecutive_subsequence(nums):
if not nums:
return []
nums = sorted(set(nums)) 19. Question: Given a list of integers, write a function to move all zeros to the end of the list
longest_streak = []
while maintaining the order of the other elements.
current_streak = [nums[0]]
20. Question: Write a function that returns the sum of two numbers represented as strings.
Your function should not use built-in arithmetic operators or functions.
22. Question: Write a function to find the longest common prefix of a list of strings.
Answer:
Answer:
23. Question: Write a function that returns the intersection of two sorted arrays. Assume each
array does not have duplicates.
21. Question: Write a function that checks if a given binary tree is a valid binary search tree.
Answer:
Answer:
def intersection_of_sorted_arrays(nums1, nums2):
class TreeNode: i, j = 0, 0
def __init__(self, value=0, left=None, right=None): intersection = []
self.value = value while i < len(nums1) and j < len(nums2):
self.left = left if nums1[i] == nums2[j]:
self.right = right intersection.append(nums1[i])
i += 1
def is_valid_bst(root, left=None, right=None): j += 1
if not root: elif nums1[i] < nums2[j]:
return True i += 1
if left and root.value <= left.value: else:
return False j += 1
if right and root.value >= right.value: return intersection
return False
return is_valid_bst(root.left, left, root) and is_valid_bst(root.right, arr1 = [1, 2, 4, 5, 6]
root, right) arr2 = [2, 3, 5, 7]
print(intersection_of_sorted_arrays(arr1, arr2)) # Output: [2, 5] visited = set([start])
while queue:
(x, y), steps = queue.popleft()
if (x, y) == end:
return steps
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
24. Question: Write a function to determine if two strings are one edit (or zero edits) away. nx, ny = x + dx, y + dy
if 0 <= nx < len(maze) and 0 <= ny < len(maze[0]) and maze[nx][ny]
Answer: == 0 and (nx, ny) not in visited:
visited.add((nx, ny))
def is_one_edit_away(s1, s2): queue.append(((nx, ny), steps + 1))
if abs(len(s1) - len(s2)) > 1: return -1
return False
maze = [
if len(s1) > len(s2): [0, 1, 0, 0, 0],
s1, s2 = s2, s1 [0, 1, 0, 1, 0],
[0, 0, 0, 1, 0],
i, j, found_difference = 0, 0, False [0, 1, 1, 1, 1],
while i < len(s1) and j < len(s2): [0, 0, 0, 0, 0]
]
if s1[i] != s2[j]:
if found_difference: start = (0, 0)
return False end = (4, 4)
print(shortest_path(maze, start, end)) # Output: 12 (or -1 if there's no
found_difference = True
path)
if len(s1) == len(s2):
i += 1
else:
i += 1
j += 1
Remember to adapt and explain your code as necessary during an interview, ensuring you
return True
understand every line and are prepared to discuss alternative solutions or optimizations.
print(is_one_edit_away("pale", "ple")) # Output: True
print(is_one_edit_away("pales", "pale")) # Output: True
print(is_one_edit_away("pale", "bale")) # Output: True
print(is_one_edit_away("pale", "bake")) # Output: False
26. Question: Write a function that returns the nth number in the Fibonacci sequence using
recursion.
Answer:
25. Question: Write a function that returns the shortest path in a maze from a start point to def fibonacci_recursive(n):
if n <= 1:
an end point, given that you can only move up, down, left, or right. The maze is represented
return n
as a 2D list where 0 represents an open path and 1 represents a wall.
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
Answer:
print(fibonacci_recursive(7)) # Output: 13
def shortest_path(maze, start, end):
if not maze or not maze[0]:
return None
from collections import deque
queue = deque([(start, 0)])
27. Question: Write a function to flatten a nested list of integers. Assume each element is top_element = stack.pop() if stack else '#'
if mapping[char] != top_element:
either an integer or a list.
return False
else:
Answer:
stack.append(char)
return not stack
def flatten(nested_list):
flat_list = [] brackets = "{[]}"
for item in nested_list: print(is_valid_brackets(brackets)) # Output: True
if isinstance(item, list):
flat_list.extend(flatten(item))
else:
flat_list.append(item)
return flat_list
30. Question: Write a function to find the two numbers in a list that sum up to a specific
nested = [1, [2, 3, [4, 5], 6], 7, [8, 9]] target.
print(flatten(nested)) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Answer:
29. Question: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if 31. Question: Write a function that reverses a string, but maintains the position of all non-
the input string is valid. An input string is valid if: alphabetic characters.
string = "ab@cd#ef$gh"
print(reverse_alphabet_only(string)) # Output: "hg@fe#dc$ba"
34. Question: Given two strings s and t , write a function to check if t is an anagram of
s .
Answer:
32. Question: Write a function to find the first non-repeated character in a string. def is_anagram(s, t):
return sorted(s) == sorted(t)
Answer:
s1 = "listen"
t1 = "silent"
def first_unique_char(s): print(is_anagram(s1, t1)) # Output: True
char_count = {}
for char in s:
char_count[char] = char_count.get(char, 0) + 1
for char in s:
if char_count[char] == 1:
return char 35. Question: Write a function to compute the factorial of a number using iteration.
return None
Answer:
string = "swiss"
print(first_unique_char(string)) # Output: "w"
def factorial_iterative(n):
result = 1
for i in range(2, n+1):
result *= i
return result
33. Question: Write a function to find all the prime numbers less than a given number n .
number = 5
Answer: print(factorial_iterative(number)) # Output: 120
def find_primes(n):
if n <= 2:
return []
primes = [True] * n As always, understanding the underlying logic and being able to explain your solution is
primes[0], primes[1] = False, False crucial during an interview. It's beneficial to discuss the trade-offs, potential optimizations,
for i in range(2, int(n ** 0.5) + 1): and edge cases of each solution.
if primes[i]:
for j in range(i * i, n, i):
primes[j] = False
return [i for i, val in enumerate(primes) if val] 36. Question: Write a function that checks if a given word is an isogram (a word with no
repeating letters).
number = 30
Answer:
for _ in range(num // val[i]):
def is_isogram(word): roman_num += syms[i]
word = word.lower() num -= val[i]
return len(word) == len(set(word)) i += 1
return roman_num
word = "background"
print(is_isogram(word)) # Output: True number = 3549
print(int_to_roman(number)) # Output: "MMMDXLIX"
37. Question: Write a function to rotate an array to the right by k steps, where k is non-
negative. 39. Question: Write a function that finds the longest common subsequence (LCS) of two
strings.
Answer:
Answer:
def rotate(nums, k):
k = k % len(nums) # in case k is larger than the length of nums def lcs(X, Y):
nums[:] = nums[-k:] + nums[:-k] m = len(X)
return nums n = len(Y)
dp = [[None] * (n + 1) for i in range(m + 1)]
array = [1,2,3,4,5,6,7]
steps = 3 for i in range(m + 1):
print(rotate(array, steps)) # Output: [5,6,7,1,2,3,4] for j in range(n + 1):
if i == 0 or j == 0:
dp[i][j] = 0
elif X[i-1] == Y[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
38. Question: Write a function to convert a given integer to its Roman numeral
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
representation. return dp[m][n]
def has_cycle(head): 43. Question: Write a function that computes the power of a number without using the built-
slow, fast = head, head in power function or the ** operator.
while fast and fast.next:
slow = slow.next Answer:
fast = fast.next.next
if slow == fast:
return True def power(base, exp):
return False if exp == 0:
return 1
# Example Usage: if exp < 0:
# node1 = ListNode(1) base = 1 / base
# node2 = ListNode(2) exp = -exp
# node3 = ListNode(3)
# node1.next = node2 result = 1
# node2.next = node3 current_product = base
# node3.next = node1 # Creates a cycle while exp > 0:
# print(has_cycle(node1)) # Output: True if exp % 2 == 1:
result = result * current_product
current_product = current_product * current_product
exp //= 2
return result
42. Question: Write a function that finds the intersection point of two linked lists. print(power(2, 3)) # Output: 8
Answer:
print(power(3, -2)) # Output: 0.1111 (or close to it) the longest substring without repeating characters)
44. Question: Write a function to validate if a given string contains only balanced When working on these questions, it's always a good idea to explore the problems in depth,
parentheses. (Only '(' and ')' are considered). analyze different approaches, and understand the time and space complexities of your
solutions.
Answer:
def is_balanced(s):
46. Question: Given a string s and a string t , find all the start indices of t 's anagrams in
stack = []
s . Strings consist of lowercase English letters only and the length of both strings s and t
for char in s:
if char == '(': will not be larger than 20,000.
stack.append(char)
elif char == ')': Answer:
if not stack:
return False
from collections import Counter
stack.pop()
return len(stack) == 0
def find_anagrams(s, t):
t_counter = Counter(t)
print(is_balanced("(())")) # Output: True
s_counter = Counter(s[:len(t)-1])
print(is_balanced("()()")) # Output: True
res = []
print(is_balanced("(()")) # Output: False
for i in range(len(t)-1, len(s)):
print(is_balanced(")(")) # Output: False
s_counter[s[i]] += 1 # include a new char in the window
if s_counter == t_counter: # This step is O(1), as there are at most
26 English letters
res.append(i-len(t)+1) # append the starting index
s_counter[s[i-len(t)+1]] -= 1 # decrease the count of oldest char in
45. Question: Write a function that returns the longest substring without repeating the window
if s_counter[s[i-len(t)+1]] == 0:
characters.
del s_counter[s[i-len(t)+1]] # remove the count if it is 0
return res
Answer:
s = "cbaebabacd"
def length_of_longest_substring(s): t = "abc"
n = len(s) print(find_anagrams(s, t)) # Output: [0, 6]
ans = 0
char_index = {} # Current index of character
i = 0 # The sliding window left pointer
for j in range(n):
if s[j] in char_index:
i = max(char_index[s[j]], i)
ans = max(ans, j - i + 1) 47. Question: Given an unsorted integer array, find the smallest missing positive integer.
char_index[s[j]] = j + 1
return ans Answer:
# Place each number in its correct position intervals = [[1, 3], [6, 9]]
for num in nums: new_interval = [2, 5]
if 1 <= num <= n: print(insert_interval(intervals, new_interval)) # Output: [[1, 5], [6, 9]]
nums[num-1], num = num, nums[num-1]
def calculate(s):
if not s:
return 0
48. Question: Given a set of non-overlapping intervals, insert a new interval into the intervals stack, num, sign = [], 0, "+"
(merge if necessary). You may assume that the intervals were initially sorted according to their for i in range(len(s)):
start times. if s[i].isdigit():
num = num * 10 + int(s[i])
Answer: if s[i] in "+-*/" or i == len(s) - 1:
if sign == "+":
stack.append(num)
def insert_interval(intervals, new_interval): elif sign == "-":
merged = [] stack.append(-num)
i, n = 0, len(intervals) elif sign == "*":
stack.append(stack.pop() * num)
# Add all the intervals starting before new_interval else: # division
while i < n and intervals[i][1] < new_interval[0]: top = stack.pop()
merged.append(intervals[i]) if top < 0:
i += 1 stack.append(-(-top // num))
else:
# Merge all overlapping intervals to one considering new_interval stack.append(top // num)
while i < n and intervals[i][0] <= new_interval[1]: num = 0
new_interval[0] = min(new_interval[0], intervals[i][0]) sign = s[i]
new_interval[1] = max(new_interval[1], intervals[i][1]) return sum(stack)
i += 1
expression = "3+2*2"
# Add the union of intervals we got
print(calculate(expression)) # Output: 7 # dictionary = WordDictionary()
# dictionary.addWord("bad")
# dictionary.addWord("dad")
# dictionary.addWord("mad")
# print(dictionary.search("pad")) # Output: False
# print(dictionary.search("bad")) # Output: True
50. Question: Design a data structure that supports the following two operations: # print(dictionary.search(".ad")) # Output: True
# print(dictionary.search("b..")) # Output: True
void addWord(word)
bool search(word)
The search function should be able to search a literal word or a regular expression string
containing only letters a-z or . . The . period should be able to represent any one letter. The complexity of problems you could be asked during an interview can vary significantly
based on the company and role. Always be prepared for both algorithmic challenges and
Answer:
more practical problems that may be closer to the actual work in the job you're applying for.
class WordDictionary:
def __init__(self): 51. Question: Given a list of words, group the anagrams together.
self.trie = {}
Answer:
def addWord(self, word):
node = self.trie
from collections import defaultdict
for w in word:
if w not in node:
def group_anagrams(words):
node[w] = {}
anagrams = defaultdict(list)
node = node[w]
for word in words:
node['$'] = True
# Use sorted word as a key. All anagrams will result in the same key.
sorted_word = ''.join(sorted(word))
def search(self, word):
anagrams[sorted_word].append(word)
def search_in_node(word, node):
return list(anagrams.values())
for i, ch in enumerate(word):
if not ch in node:
words = ["eat", "tea", "tan", "ant", "bat"]
# If the current character is '.', check all possible
print(group_anagrams(words)) # Output: [['eat', 'tea'], ['tan', 'ant'],
nodes at this level
['bat']]
if ch == '.':
for x in node:
if x != '$' and search_in_node(word[i + 1:],
node[x]):
Time Complexity:
return True
# if no nodes lead to answer, or the current character !=
Sorting each word takes O(KlogK) where K is the maximum length of a word.
'.'
return False Doing this for all words takes O(NKlogK) where N is the number of words.
# if the character is found, go down to the next level in trie
node = node[ch]
return '$' in node
52. Question: Given an array nums and a target value, find the two numbers in the array that
return search_in_node(word, self.trie) sum up to the target value.
Answer:
Time Complexity:
class TreeNode:
O(N) where N is the number of elements in the array. def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
53. Question: Find the longest palindromic substring in a string.
def serialize(root):
Answer: def helper(node):
if not node:
return ["null"]
def longest_palindrome(s): return [str(node.val)] + helper(node.left) + helper(node.right)
if not s:
return "" return ','.join(helper(root))
s = "babad"
Time Complexity:
Both serialization and deserialization are O(N) where N is the number of nodes in the if t < 0: return False
slist, n = SortedList(), len(nums)
tree.
for i in range(n):
if i > k: slist.remove(nums[i - k - 1])
pos1 = slist.bisect_left(nums[i] - t)
55. Question: Determine if a given binary tree is a valid binary search tree. pos2 = slist.bisect_right(nums[i] + t)
return True
return helper(root) 57. Question: Find the kth largest element in an unsorted array.
56. Question: Given an array of integers, find out whether there are two distinct indices i
Time Complexity:
and j in the array such that the absolute difference between nums[i] and nums[j] is at
most t and the absolute difference between i and j is at most k . O(N log k) where N is the number of elements in the array.
Answer:
58. Question: Given a non-empty string s and a dictionary wordDict containing a list of non-
from sortedcontainers import SortedList
empty words, determine if s can be segmented into a space-separated sequence of one or
def contains_nearby_almost_duplicate(nums, k, t): more dictionary words.
Answer: Time Complexity:
Time Complexity:
59. Question: Given a sorted array and a target value, return the index if the target is found. If
not, return the index where it would be if it were inserted in order.
Remember, these solutions are efficient for the given problems, but some might have
Answer: alternative methods to approach them. Always try to think about edge cases, and sometimes,
the interviewer might be interested in a specific method even if it's not the most optimal one.
def search_insert(nums, target):
left, right = 0, len(nums) - 1
while left <= right: 61. Question: Given an array of integers, every element appears twice except for one. Find
mid = (left + right) // 2
that single one.
if nums[mid] == target:
return mid
elif nums[mid] < target:
Answer:
left = mid + 1
else: def singleNumber(nums):
right = mid - 1 result = 0
return left for num in nums:
result ^= num
nums = [1, 3, 5, 6] return result
target = 5
print(search_insert(nums, target)) # Output: 2 nums = [4, 1, 2, 1, 2]
print(singleNumber(nums)) # Output: 4
Time Complexity:
64. Question: You are given an n x n 2D matrix representing an image. Rotate the image by
O(N) where N is the number of elements in the array.
90 degrees (clockwise).
Answer:
62. Question: Write a function to determine the number of bits you would need to flip to
convert integer A to integer B. def rotate(matrix):
n = len(matrix)
Answer: # Transpose the matrix
for i in range(n):
for j in range(i, n):
def bitSwapRequired(A, B):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
count = 0
c = A ^ B # c will have 1s wherever A and B are different
# Reverse the columns
while c:
for row in matrix:
count += c & 1
row.reverse()
c >>= 1
return count
matrix = [
[1, 2, 3],
A = 29 # 11101
[4, 5, 6],
B = 15 # 01111
[7, 8, 9]
print(bitSwapRequired(A, B)) # Output: 2
]
rotate(matrix)
print(matrix) # Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Time Complexity:
Answer:
65. Question: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if
the input string is valid. An input string is valid if the brackets are closed in the correct order.
from collections import Counter
Answer:
def is_permutation(str1, str2):
return Counter(str1) == Counter(str2)
def isValid(s):
str1 = "listen" stack = []
str2 = "silent" mapping = {")": "(", "}": "{", "]": "["}
print(is_permutation(str1, str2)) # Output: True for char in s:
if char in mapping:
top_element = stack.pop() if stack else '#'
if mapping[char] != top_element:
Time Complexity: return False
else:
O(N), where N is the length of the longer string. stack.append(char)
return not stack
s = "{[]}" class ListNode:
print(isValid(s)) # Output: True def __init__(self, x):
self.val = x
self.next = None
Time Complexity:
66. Question: Write a function to detect a cycle in a linked list.
O(N), where N is the number of nodes in the linked list.
Answer:
class ListNode: 68. Question: Implement a basic calculator to evaluate a simple expression string containing
def __init__(self, x): non-negative integers, '+', '-', '*', and '/' operators. Assume the expression is always valid.
self.val = x
self.next = None Answer:
def hasCycle(head):
slow, fast = head, head def calculate(s):
while fast and fast.next: stack, num, sign = [], 0, '+'
slow = slow.next for i, c in enumerate(s):
fast = fast.next.next if c.isdigit():
if slow == fast: num = num * 10 + int(c)
return True if c in "+-*/" or i == len(s) - 1:
return False if sign == '+':
stack.append(num)
elif sign == '-':
stack.append(-num)
Time Complexity: elif sign == '*':
stack[-1] *= num
O(N), where N is the number of nodes in the linked list. elif sign == '/':
stack[-1] = int(stack[-1] / num)
num, sign = 0, c
return sum(stack)
67. Question: Given a sorted linked list, delete all duplicates such that each element appears
only once. s = "3+2*2"
print(calculate(s)) # Output: 7
Answer:
Time Complexity:
def flatten_dictionary(d, parent_key='', sep='.'):
items = {}
O(N), where N is the length of the string.
for k, v in d.items():
new_key = f"{parent_key}{sep}{k}" if parent_key else k
if isinstance(v, dict):
69. Question: Design and implement a TwoSum class. It should support the following items.update(flatten_dictionary(v, new_key, sep=sep))
else:
operations: add and find .
items[new_key] = v
return items
add : Add the number to an internal data structure.
find : Find if there exists any pair of numbers which sum is equal to the value. nested_dict = {
"a": 1,
Answer: "b": {
"c": 2,
"d": {
class TwoSum:
"e": 3
}
def __init__(self):
}
self.data = {}
}
print(flatten_dictionary(nested_dict)) # Output: {'a': 1, 'b.c': 2, 'b.d.e':
def add(self, number):
3}
if number in self.data:
self.data[number] += 1
else:
self.data[number] = 1 Time Complexity:
def find(self, value): O(N), where N is the total number of keys in the dictionary (including nested keys).
for num in self.data:
complement = value - num
if complement in self.data:
if complement != num or self.data[num] > 1: 71. Question: Find the longest substring without repeating characters.
return True
return False Answer:
def length_of_longest_substring(s):
Time Complexity: n = len(s)
set_ = set()
add operation: O(1) ans = 0
i, j = 0, 0
find operation: O(N), where N is the number of unique numbers added so far.
while i < n and j < n:
if s[j] not in set_:
set_.add(s[j])
j += 1
70. Question: Write a function to flatten a nested dictionary. Namespace the keys with a
ans = max(ans, j - i)
period.
else:
set_.remove(s[i])
Answer: i += 1
return ans
s = "abcabcbb"
print(length_of_longest_substring(s)) # Output: 3
73. Question: Write a function to match string s against pattern p, where p can have
characters and also . which matches any character, and * which matches zero or more of
the preceding element.
Time Complexity:
Answer:
O(2N) = O(N), where N is the length of the string. The worst case will be checking each
character twice with i and j.
def is_match(s, p):
if not p:
return not s
72. Question: Serialize and deserialize a binary tree.
first_match = bool(s) and p[0] in {s[0], '.'}
Answer:
if len(p) >= 2 and p[1] == '*':
return (is_match(s, p[2:]) or
class TreeNode: first_match and is_match(s[1:], p))
def __init__(self, x): else:
self.val = x return first_match and is_match(s[1:], p[1:])
self.left = None
self.right = None s = "mississippi"
p = "mis*is*p*."
class Codec: print(is_match(s, p)) # Output: False
data_list = data.split(',')
def find_peak_element(nums):
return helper(data_list)
l, r = 0, len(nums) - 1
while l < r:
mid = (l + r) // 2
if nums[mid] < nums[mid + 1]:
Time Complexity:
l = mid + 1
else:
Serialize: O(N), where N is the number of nodes.
r = mid
Deserialize: O(N), where N is the number of nodes. return l
nums = [1, 2, 3, 4, 5, 6, 7, 5, 4, 3, 2] from collections import deque
print(find_peak_element(nums)) # Output: 6
def shortest_path_binary_matrix(grid):
if not grid or not grid[0] or grid[0][0] or grid[-1][-1]:
return -1
Time Complexity:
n, m = len(grid), len(grid[0])
O(log N), where N is the number of elements in the array. directions = [(0, 1), (1, 0), (1, 1), (-1, -1), (0, -1), (-1, 0), (1, -1),
(-1, 1)]
queue = deque([(0, 0, 1)])
75. Question: Implement the strStr() function. Return the index of the first occurrence of while queue:
needle in haystack, or -1 if needle is not part of haystack. x, y, dist = queue.popleft()
if x == n - 1 and y == m - 1:
Answer: return dist
for dx, dy in directions:
nx, ny = x + dx, y + dy
def strStr(haystack, needle): if 0 <= nx < n and 0 <= ny < m and not grid[nx][ny]:
if not needle: grid[nx][ny] = 1
return 0 queue.append((nx, ny, dist + 1))
needle_length = len(needle)
for i in range(len(haystack) - needle_length + 1): return -1
if haystack[i:i + needle_length] == needle:
return i grid = [[0,0,0],[1,1,0],[1,1,0]]
return -1 print(shortest_path_binary_matrix(grid)) # Output: 4
haystack = "hello"
needle = "ll"
print(strStr(haystack, needle)) # Output: 2
Time Complexity:
O((N-M) * M), where N is the length of the haystack and M is the length of the needle.
77. Question: Design a data structure that supports the following two operations: void
addWord(word) and bool search(word) . The search method can search a literal word or a
I hope these questions and solutions help in preparing for technical interviews. Remember to regular expression string containing only letters a-z or . . A . means it can represent any
explain your approach and thought process before diving into code. It's as much about one-letter.
problem-solving as it is about coding.
Answer:
class TrieNode:
76. Question: Find the shortest path in a binary matrix from the top-left corner to the def __init__(self):
bottom-right corner. You can move up, down, left, right, and diagonally if the adjacent cells self.children = {}
contain a 0. The path should avoid cells with a 1. self.is_end = False
80. Question: Find if a given string can be formed by a sequence of one or more palindrome
Time Complexity:
strings.
addWord : O(L), where L is the length of the word.
Answer:
search : In the worst case, O(N*26^L), where L is the length of the word and N is the
number of inserted words.
def can_form_palindrome(s):
from collections import Counter
count = Counter(s)
78. Question: Find the kth largest element in an unsorted array. return sum(v % 2 for v in count.values()) <= 1
Answer: s = "aabb"
print(can_form_palindrome(s)) # Output: True
These questions cover various topics and data structures often encountered in interviews.
Remember to always discuss the problem, clarify any assumptions, and communicate your
approach before diving into coding.