0% found this document useful (0 votes)
72 views23 pages

Python Ussecases Interview Based Questions: The-Grand-Complete-Data-Science-Materials

The document contains a collection of Python interview questions and their corresponding solutions, covering various topics such as recursion, string manipulation, data structures, and algorithms. Each question is followed by a detailed answer, including code snippets that demonstrate the implementation of the solutions. This resource serves as a comprehensive guide for preparing for Python-related technical interviews.

Uploaded by

sharath.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views23 pages

Python Ussecases Interview Based Questions: The-Grand-Complete-Data-Science-Materials

The document contains a collection of Python interview questions and their corresponding solutions, covering various topics such as recursion, string manipulation, data structures, and algorithms. Each question is followed by a detailed answer, including code snippets that demonstrate the implementation of the solutions. This resource serves as a comprehensive guide for preparing for Python-related technical interviews.

Uploaded by

sharath.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

krishnaik06 / The-Grand-Complete-Data-Science-Materials Public def factorial(n):

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

krishnaik06 Add files via upload 3 weeks ago

2099 lines (1591 loc) · 90.7 KB


3. Question: You are given a list of strings. Write a function to filter out all strings that are
palindromes.
Preview Code Blame Raw

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.

4. Question: Given a string, write a function to check if it is an anagram of another string.


def second_highest(numbers):
numbers = list(set(numbers)) Answer: An anagram is a word or phrase formed by rearranging the letters of a different word
numbers.sort()
or phrase, typically using all the original letters exactly once.
return numbers[-2]

numbers = [1, 3, 2, 4, 4, 5, 6, 6] def are_anagrams(s1, s2):


print(second_highest(numbers)) # Output: 5 return sorted(s1) == sorted(s2)

str1 = "listen"
str2 = "silent"
print(are_anagrams(str1, str2)) # Output: True

2. Question: Write a function to compute the factorial of a number using recursion.

Answer:

5. Question: Write a function to flatten a nested list.


Answer:
8. Question: Write a Python function to merge two dictionaries. If both dictionaries have the
def flatten(lst): same key, prefer the second dictionary's value.
result = []
for i in lst: Answer:
if isinstance(i, list):
result.extend(flatten(i))
def merge_dicts(dict1, dict2):
else:
merged = dict1.copy()
result.append(i)
merged.update(dict2)
return result
return merged

nested_list = [1, [2, 3, [4, 5]], 6]


dict1 = {'a': 1, 'b': 2}
print(flatten(nested_list)) # Output: [1, 2, 3, 4, 5, 6]
dict2 = {'b': 3, 'c': 4}
print(merge_dicts(dict1, dict2)) # Output: {'a': 1, 'b': 3, 'c': 4}

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.

Answer: def most_repeated(s):


char_count = {}
for char in s:
def common_elements(list1, list2): if char in char_count:
return list(set(list1) & set(list2)) char_count[char] += 1
else:
list1 = [1, 2, 3, 4, 5] char_count[char] = 1
list2 = [4, 5, 6, 7, 8] max_char = max(char_count, key=char_count.get)
print(common_elements(list1, list2)) # Output: [4, 5] return max_char

string = "aabbbcdddde"
print(most_repeated(string)) # Output: 'd'

7. Question: Write a function that returns the number of words in a string.

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

13. Question: Write a function to compute the Fibonacci series up to n.

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]]

for i in range(1, len(nums)):


Answer:
if nums[i] - nums[i - 1] == 1:
current_streak.append(nums[i]) def move_zeros(nums):
else: count = nums.count(0)
if len(current_streak) > len(longest_streak): nums = [num for num in nums if num != 0]
longest_streak = current_streak nums.extend([0] * count)
current_streak = [nums[i]] return nums

return longest_streak if len(longest_streak) > len(current_streak) else numbers = [1, 2, 0, 4, 0, 5, 6, 0]


print(move_zeros(numbers)) # Output: [1, 2, 4, 5, 6, 0, 0, 0] # Example usage:
root = TreeNode(2, TreeNode(1), TreeNode(3))
print(is_valid_bst(root)) # Output: True

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:

def add_strings(num1, num2):


res, carry, i, j = "", 0, len(num1) - 1, len(num2) - 1 def longest_common_prefix(strings):
while i >= 0 or j >= 0 or carry: if not strings:
n1 = int(num1[i]) if i >= 0 else 0 return ""
n2 = int(num2[j]) if j >= 0 else 0 prefix = strings[0]
temp_sum = n1 + n2 + carry for s in strings[1:]:
res = str(temp_sum % 10) + res while not s.startswith(prefix):
carry = temp_sum // 10 prefix = prefix[:-1]
i, j = i - 1, j - 1 return prefix
return res
strings = ["flower", "flow", "flight"]
n1 = "123" print(longest_common_prefix(strings)) # Output: "fl"
n2 = "789"
print(add_strings(n1, n2)) # Output: "912"

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:

def two_sum(nums, target):


num_dict = {}
28. Question: Write a function to check if a given string is a palindrome. for i, num in enumerate(nums):
complement = target - num
Answer: if complement in num_dict:
return [num_dict[complement], i]
num_dict[num] = i
def is_palindrome(s): return None
return s == s[::-1]
numbers = [2, 7, 11, 15]
string = "radar" target_value = 9
print(is_palindrome(string)) # Output: True print(two_sum(numbers, target_value)) # Output: [0, 1]

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.

Open brackets are closed by the same type of brackets. Answer:


Open brackets are closed in the correct order.
def reverse_alphabet_only(s):
Answer: s = list(s)
i, j = 0, len(s) - 1
while i < j:
def is_valid_brackets(s):
stack = [] if not s[i].isalpha():
mapping = {")": "(", "}": "{", "]": "["} i += 1
elif not s[j].isalpha():
for char in s:
if char in mapping: j -= 1
else:
s[i], s[j] = s[j], s[i] print(find_primes(number)) # Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
i += 1
j -= 1
return ''.join(s)

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]

Answer: str1 = "ABCBDAB"


str2 = "BDCAB"
print(lcs(str1, str2)) # Output: 4 (because "BCAB" is a common subsequence)
def int_to_roman(num):
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4, 1
] 40. Question: Write a function to find the square root of a number using the Newton-
syms = [
Raphson method.
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
Answer:
"X", "IX", "V", "IV",
"I"
] def sqrt_newton(n, tolerance=1e-10, guess=1.0):
roman_num = '' while True:
i = 0 better_guess = (guess + n / guess) / 2
while num > 0: if abs(better_guess - guess) < tolerance: # Close enough
return better_guess
guess = better_guess def get_intersection_node(headA, headB):
if not headA or not headB:
number = 25 return None
print(sqrt_newton(number)) # Output: 5.0 (or very close to it)
ptrA, ptrB = headA, headB

while ptrA != ptrB:


ptrA = ptrA.next if ptrA else headB
ptrB = ptrB.next if ptrB else headA
When practicing for interviews, ensure you understand each problem and its solution deeply.
The key is to not only get the correct answer but to also explain the reasoning behind your return ptrA
approach, its complexities, and potential improvements.
# Assuming ListNode class definition from the previous question
# Example Usage:
# A: 1 -> 2 -> 3 -> 4
41. Question: Write a function that detects a cycle in a linked list. # ↘
# 5 -> 6 -> 7
Answer: # ↗
# B: 8 -> 9
# print(get_intersection_node(A, B).value) # Output: 5
class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next

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:

print(length_of_longest_substring("abcabcbb")) # Output: 3 (because "abc" is


merged.append(new_interval)
def first_missing_positive(nums):
n = len(nums) # Add all the rest
while i < n:
# First, mark all negative values as 'n + 1' merged.append(intervals[i])
for i in range(n): i += 1
if nums[i] <= 0:
nums[i] = n + 1 return merged

# 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]

# The first place where its number is not correct


for i, num in enumerate(nums, 1):
if num != i:
return i 49. Question: Implement a basic calculator to evaluate a simple expression string containing
non-negative integers, '+', '-', '*', and '/' operators. You can assume the given expression is
return n + 1 always valid.

nums = [3, 4, -1, 1] Answer:


print(first_missing_positive(nums)) # Output: 2

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.

# Example Usage: Answer:


print(longest_palindrome(s)) # Output: "bab" or "aba"
def two_sum(nums, target):
num_to_index = {}
for i, num in enumerate(nums):
if target - num in num_to_index: Time Complexity:
return [num_to_index[target - num], i]
num_to_index[num] = i O(N^2) where N is the length of the string.

nums = [2, 7, 11, 15]


target = 9
print(two_sum(nums, target)) # Output: [0, 1] 54. Question: Implement a function to serialize and deserialize a binary tree.

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))

longest = "" def deserialize(data):


for i in range(len(s)): def helper(nodes):
# Odd length palindromes val = nodes.pop(0)
p1 = expand_from_center(s, i, i) if val == "null":
if len(p1) > len(longest): return None
longest = p1 node = TreeNode(int(val))
node.left = helper(nodes)
# Even length palindromes node.right = helper(nodes)
p2 = expand_from_center(s, i, i + 1) return node
if len(p2) > len(longest):
longest = p2 nodes = data.split(',')
return helper(nodes)
return longest
# Usage:
def expand_from_center(s, l, r): # node = TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4), TreeNode(5)))
while l >= 0 and r < len(s) and s[l] == s[r]: # s = serialize(node)
l -= 1 # print(s) # Output: "1,2,null,null,3,4,null,null,5,null,null"
r += 1 # new_node = deserialize(s)
return s[l + 1:r]

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)

Answer: if pos1 != pos2:


return True

def is_valid_bst(root): slist.add(nums[i])


def helper(node, lower=float('-inf'), upper=float('inf')): return False
if not node:
return True nums = [1, 2, 3, 1]
k = 3
val = node.val t = 0
if val <= lower or val >= upper: print(contains_nearby_almost_duplicate(nums, k, t)) # Output: True
return False

if not helper(node.right, val, upper):


return False Time Complexity:
if not helper(node.left, lower, val):
return False O(N log(min(N, K))) where N is the number of elements in the array.

return True

return helper(root) 57. Question: Find the kth largest element in an unsorted array.

# Assuming TreeNode class definition from the previous question Answer:


# Example Usage:
# node = TreeNode(2, TreeNode(1), TreeNode(3))
import heapq
# print(is_valid_bst(node)) # Output: True

def find_kth_largest(nums, k):


return heapq.nlargest(k, nums)[-1]
Time Complexity:
nums = [3, 2, 1, 5, 6, 4]
k = 2
O(N) where N is the number of nodes in the tree.
print(find_kth_largest(nums, k)) # Output: 5

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:

O(log N) where N is the number of elements in the array.


def word_break(s, wordDict):
wordSet, n = set(wordDict), len(s)
dp = [False] * (n + 1)
dp[0] = True 60. Question: Rotate an array to the right by k steps.

for i in range(1, n + 1): Answer:


for j in range(i):
if dp[j] and s[j:i] in wordSet:
dp[i] = True def rotate(nums, k):
break n = len(nums)
return dp[-1] k %= n
nums[:] = nums[-k:] + nums[:-k]
s = "leetcode"
wordDict = ["leet", "code"] nums = [1, 2, 3, 4, 5, 6, 7]
print(word_break(s, wordDict)) # Output: True k = 3
rotate(nums, k)
print(nums) # Output: [5, 6, 7, 1, 2, 3, 4]

Time Complexity:

O(N^2) where N is the length of the string. Time Complexity:

O(N) where N is the number of elements in the array.

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 &amp; 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:

O(1), since the size of the integers is fixed (typically 32 or 64 bits).


Time Complexity:

O(N^2), where N is the number of rows (or columns) in the matrix.


63. Question: Given two strings, write a method to decide if one is a permutation of the other.

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: def deleteDuplicates(head):


current = head
O(N), where N is the length of the string. while current and current.next:
if current.next.val == current.val:
current.next = current.next.next
else:
As always, during an interview, focus not only on the solution but also on communicating current = current.next
your thought process, justifying your choices, and being open to suggestions or alternative return head
approaches.

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

def serialize(self, root):


if not root:
return 'None' Time Complexity:
return str(root.val) + ',' + self.serialize(root.left) + ',' +
self.serialize(root.right) In the worst case, the time complexity is O((N+P)2^(N+P/2)), where N is the length of the
string and P is the length of the pattern.
def deserialize(self, data):
def helper(data_list):
if data_list[0] == 'None':
data_list.pop(0) 74. Question: Find the peak element in an array. A peak element is an element which is
return None greater than or equal to its neighbors. Assume the array is sorted in ascending order, and
root = TreeNode(data_list[0])
then a peak is found, then it is sorted in descending order. Also, assume the array may have
data_list.pop(0)
root.left = helper(data_list) duplicates.
root.right = helper(data_list)
return root Answer:

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), where N and M are the dimensions of the grid.


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

Answer: class WordDictionary:


def __init__(self):
self.root = TrieNode() nums = [3,2,3,1,2,4,5,5,6]
k = 4
def addWord(self, word): print(findKthLargest(nums, k)) # Output: 4
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode() Time Complexity:
node = node.children[ch]
node.is_end = True O(Nlogk), where N is the length of the nums array.

def search(self, word):


return self.match(word, 0, self.root)
79. Question: Given a list of integers, return the number of good pairs. A pair (i, j) is
def match(self, word, index, node): called good if nums[i] == nums[j] and i < j .
if index == len(word):
return node.is_end Answer:
if word[index] != '.':
return word[index] in node.children and self.match(word, index +
def numIdenticalPairs(nums):
1, node.children[word[index]])
from collections import Counter
for child in node.children.values():
count = Counter(nums)
if self.match(word, index + 1, child):
return sum(v*(v-1)//2 for v in count.values())
return True
return False
nums = [1,2,3,1,1,3]
print(numIdenticalPairs(nums)) # Output: 4
wd = WordDictionary()
wd.addWord("bad")
wd.addWord("dad")
wd.addWord("mad")
Time Complexity:
print(wd.search("pad")) # Output: False
print(wd.search("bad")) # Output: True
O(N), where N is the length of the nums list.
print(wd.search(".ad")) # Output: True

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

def findKthLargest(nums, k):


import heapq
return heapq.nlargest(k, nums)[-1] Time Complexity:
O(N), where N is the length of the string s.

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.

You might also like