Interview Questions

1) Given a list of integers, find the element that appears most frequently. If there is a tie, return t


from collections import Counter

def most_frequent_element(lst):
    freq = Counter(lst)
    most_common = min(freq.items(), key=lambda x: (-x[1], x[0]))
    return most_common[0]

# Example usage:
lst = [3, 1, 3, 2, 3, 4, 1, 1, 1]
print(most_frequent_element(lst))  # Output: 1

Explanation:

  • Use Counter from the collections module to count the frequency of each element.
  • Use min to find the most frequent element, with a custom key that prioritizes higher frequency and, in case of a tie, the smallest element.

2) Given a string containing parentheses, determine if the parentheses are balanced. A string is consid


def is_balanced(s):
    stack = []
    for char in s:
        if char == '(':
            stack.append(char)
        elif char == ')':
            if not stack or stack.pop() != '(':
                return False
    return len(stack) == 0

# Example usage:
print(is_balanced("(())"))  # Output: True
print(is_balanced("(()"))   # Output: False

Explanation:

  • Use a stack to keep track of opening parentheses.
  • When encountering a closing parenthesis, check if there is a matching opening parenthesis in the stack.

3) Given two arrays of integers, return the intersection of the two arrays (i.e., the elements that app


def intersection(arr1, arr2):
    return list(set(arr1) & set(arr2))

# Example usage:
arr1 = [1, 2, 2, 1]
arr2 = [2, 2]
print(intersection(arr1, arr2))  # Output: [2]

Explanation:

  • Convert both arrays to sets to remove duplicates and then use the set intersection (&) operator to find common elements.

4) Given a singly linked list, reverse the list.


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverse_linked_list(head):
    prev = None
    current = head
    while current:
        next_node = current.next
        current.next = prev
        prev = current
        current = next_node
    return prev

# Example usage:
# Linked list: 1 -> 2 -> 3
head = ListNode(1, ListNode(2, ListNode(3)))
new_head = reverse_linked_list(head)

Explanation:

  • Use three pointers: prev, current, and next_node to reverse the list in one pass.

5) Given a string, find the length of the longest substring without repeating characters.


def length_of_longest_substring(s):
    char_set = set()
    left = 0
    max_length = 0

    for right in range(len(s)):
        while s[right] in char_set:
            char_set.remove(s[left])
            left += 1
        char_set.add(s[right])
        max_length = max(max_length, right - left + 1)
    
    return max_length

# Example usage:
print(length_of_longest_substring("abcabcbb"))  # Output: 3

Explanation:

  • Use a sliding window with two pointers (left and right) and a set to track characters in the window.
  • If a character is repeated, move the left pointer to the right until the character is removed.

6) Given two sorted linked lists, merge them into a single sorted linked list.


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def merge_sorted_lists(l1, l2):
    dummy = ListNode()
    current = dummy
    while l1 and l2:
        if l1.val < l2.val:
            current.next = l1
            l1 = l1.next
        else:
            current.next = l2
            l2 = l2.next
        current = current.next
    
    # Append remaining nodes
    current.next = l1 if l1 else l2
    return dummy.next

# Example usage:
# l1: 1 -> 2 -> 4
# l2: 1 -> 3 -> 4

Explanation:

  • Use a dummy node to simplify the merging process.
  • Traverse both lists, choosing the smaller value each time.

7) Given an array, return a list of duplicate elements in the array.


def find_duplicates(nums):
    seen = set()
    duplicates = []
    for num in nums:
        if num in seen:
            duplicates.append(num)
        else:
            seen.add(num)
    return duplicates

# Example usage:
print(find_duplicates([1, 2, 3, 1, 4, 5, 2]))  # Output: [1, 2]

Explanation:

  • Use a set to track seen elements and append to duplicates when an element is encountered again.

8) Given an array of integers, find two numbers that add up to a target sum.


def two_sum(nums, target):
    num_map = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in num_map:
            return [num_map[complement], i]
        num_map[num] = i

# Example usage:
print(two_sum([2, 7, 11, 15], 9))  # Output: [0, 1]

Explanation:

  • Use a hash map to store the difference (target - num) and its index.
  • When a complement is found, return the indices.

9) Given an array of integers, find the Kth largest element.


import heapq

def find_kth_largest(nums, k):
    return heapq.nlargest(k, nums)[-1]

# Example usage:
print(find_kth_largest([3, 2, 1, 5, 6, 4], 2))  # Output: 5

Explanation:

  • Use Python's heapq.nlargest() to get the K largest elements and return the last element.