Explain the Two Pointers Technique.
Technique: Uses two pointers which could move towards each other or in the same direction to iterate through the data structure (array or linked list) to solve problems.
Applications: Find a pair in an array that sums up to a target value, reverse an array, remove duplicates from a sorted array.
What is the Sliding Window Technique?
Concept: The Sliding Window technique involves creating a window that can either grow or shrink in size as it slides over data structures like arrays or strings to capture sub-elements.
Classic Problems: Maximum sum of any contiguous subarray of size ‘k’, smallest subarray with a given sum, longest substring with ‘k’ distinct characters.
What is the Top K Elements Pattern?
Concept: This pattern deals with problems that ask to find a set of ‘K’ elements out of a collection that meet certain criteria.
Techniques: Often solved using a Heap or the Quick Select algorithm to efficiently find the required elements.
Example Problems: Find K largest (or smallest) elements in an array, K closest points to the origin.
How to create a sliding window in a list?
end - start + 1
What is Pigeon-hole principle?
How do you reverse a singly linked list in Python?
To reverse a singly linked list, you need to change the direction of the pointers. Iterate through the list and, for each node, switch its next pointer to point to the previous node.
def reverseLinkedList(head: ListNode) -> ListNode:
prev, curr = None, head
while curr:
next_temp = curr.next
curr.next = prev
prev = curr
curr = next_temp
return prevShorter version:head.next, head, prev = prev, head.next, head
What property does the in-order traversal of a Binary Search Tree (BST) demonstrate, and how does it relate to the elements’ order?
The in-order traversal of a Binary Search Tree (BST) demonstrates the property of producing the elements of the tree in a sorted ascending order. This traversal method visits the left subtree first, then the current node, and finally the right subtree.
Due to the BST’s inherent property where the left child is less than the parent node, and the right child is greater than the parent node, in-order traversal naturally processes the nodes in their increasing value order.
This characteristic makes in-order traversal especially useful for operations that require sorted data, such as searching for a specific value or printing all values in order.