If you’re preparing for interviews at top MNCs like Google, Amazon, Microsoft, or Meta, mastering Data Structures and Algorithms (DSA) is crucial. These companies often test your problem-solving skills using classic Dsa Questions. Here’s a list of the top 10 most frequently asked questions, complete with detailed solutions and explanations.
1. Reverse a Linked List
Problem: Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.
Solution: Approach for Reversing a Subsection of a Linked List. The goal is to reverse a part of the linked list between positions left and right. Here’s the high-level approach:
Steps to Solve the Problem
- Handle Edge Cases:
- If
headisNULL, returnNULL(empty list). - If the
leftandrightpositions are the same, return the original list (no reversal needed).
- If
- Traverse to the Starting Point:
- Use a pointer
tempto traverse the list until positionleft. - Maintain a
prevpointer to track the node just beforeleft.
- Use a pointer
- Locate the Endpoint:
- Use another pointer
temp1to traverse the list until positionright. - Store the node immediately after
rightin a pointernextfor reconnection later.
- Use another pointer
- Disconnect the Sublist:
- Temporarily break the linked list into three parts:
- Before
left - Between
leftandright - After
right
- Before
- Temporarily break the linked list into three parts:
- Reverse the Sublist:
- Use the
reversefunction to reverse the nodes betweenleftandright.
- Use the
- Reconnect the List:
- Connect the reversed sublist back to the “before” and “after” parts of the original list.
- Return the New Head:
- If the
prevpointer isNULL, the head of the reversed sublist becomes the new head of the list. - Otherwise, reconnect
prevto the reversed sublist and return the originalhead.
- If the
2. Find the Intersection of Two Arrays
Problem: Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
Solution: The task is to find the intersection of two arrays, nums1 and nums2, where each element in the result must appear as many times as it shows in both arrays. The solution uses a two-pointer technique after sorting the arrays.
Steps to Solve the Problem
- Sort Both Arrays:
- Sort
nums1andnums2in ascending order using the built-insortfunction. - Sorting helps in comparing elements sequentially and efficiently.
- Sort
- Initialize Two Pointers:
ifor traversingnums1.jfor traversingnums2.
- Traverse Both Arrays:
- Use a
whileloop that continues as long asiis within the bounds ofnums1andjis within the bounds ofnums2.
- Use a
- Compare Elements:
- If
nums1[i] < nums2[j]: Incrementi(move the pointer innums1forward). - If
nums1[i] > nums2[j]: Incrementj(move the pointer innums2forward). - If
nums1[i] == nums2[j]:- Add the common element (
nums1[i]) to the result vectorans. - Increment both
iandj.
- Add the common element (
- If
- Return the Result:
- After the loop ends,
anscontains the elements that appear in both arrays, with their frequencies matching.
- After the loop ends,
3. Merge Two Sorted Arrays
Problem: The task is to merge two sorted arrays, nums1 and nums2, into one sorted array, where the merged array is stored in nums1. The function modifies nums1 in-place to save space.
Steps to Solve the Problem
- Understand the Inputs:
nums1: A vector with enough space to hold elements of both arrays (mvalid elements followed bynempty slots).nums2: A vector containingnelements.m: Number of valid elements innums1.n: Number of elements innums2.
- Start from the End:
- Use three pointers:
istarts at the last valid element innums1(m−1).jstarts at the last element innums2(n−1).kstarts at the last position innums1(m+n−1).
- Use three pointers:
- Merge in Reverse:
- Compare
nums1[i]andnums2[j]. - Place the larger value at the current position
kinnums1. - Decrement the respective pointer (
iorj) andk.
- Compare
- Handle Remaining Elements in
nums2:- If there are elements left in
nums2(whenj >= 0), copy them tonums1.
- If there are elements left in
- Return the Result:
- The modified
nums1now contains all elements from both arrays, sorted in ascending order.
- The modified
4. Longest Substring Without Repeating Characters
Problem: Given a string S, find the length of the longest substring without repeating characters.
Solution: This problem involves finding the longest substring in a string s such that no characters are repeated. The solution uses the sliding window technique with the help of an auxiliary array to track the last seen indices of characters.
Steps to Solve the Problem
- Initialize Data Structures:
- Create a
maparray of size 256 (for all ASCII characters) initialized to-1. This stores the last seen index of each character in the string. - Initialize variables:
left: Starting index of the current substring.right: Pointer to iterate through the string.length: Stores the maximum length of a substring found so far.
- Create a
- Iterate Through the String:
- Use
rightas a pointer to traverse the string.
- Use
- Handle Repeated Characters:
- If the current character
s[right]has been seen before (map[s[right]] != -1), update theleftpointer to skip over the previous occurrence. Useleft = max(map[s[right]] + 1, left)to ensureleftonly moves forward.
- If the current character
- Update Last Seen Index:
- Update
map[s[right]]with the current indexright.
- Update
- Calculate the Current Window Length:
- Compute the current window length as
right - left + 1and updatelengthto store the maximum value found so far.
- Compute the current window length as
- Return the Result:
- After processing the string,
lengthcontains the length of the longest substring without repeating characters.
- After processing the string,
5. Find the Cycle in a Linked List
Problem: Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
Solution: The problem is to detect if a cycle exists in a linked list, and if it does, return the starting node of the cycle. The solution employs Floyd’s Cycle Detection Algorithm, also known as the tortoise and hare algorithm, which uses two pointers (slow and fast) to traverse the list.
Steps to Solve the Problem
- Initialize Two Pointers:
slowandfastpointers are both initialized to point to theheadof the linked list.
- Traverse the Linked List:
- Move
slowone step at a time (slow = slow->next). - Move
fasttwo steps at a time (fast = fast->next->next).
- Move
- Detect a Cycle:
- If
slowandfastpointers meet, a cycle exists. Break out of the loop. - If
fastbecomesNULLorfast->nextbecomesNULL, the list has no cycle; returnNULL.
- If
- Find the Starting Node of the Cycle:
- Reset
slowtohead. - Move both
slowandfastone step at a time until they meet. The meeting point is the start of the cycle.
- Reset
- Return the Result:
- Return the node where
slowandfastmeet after the second traversal. - If no cycle is detected, return
NULL.
- Return the node where
6. Maximum Subarray (Kadane’s Algorithm)
Problem: Given an integer array nums, find the subarray with the largest sum, and return its sum.
Solution: This problem is about finding the maximum sum of a contiguous subarray in a given array of integers. The solution uses Kadane’s Algorithm, which efficiently computes the result in linear time by dynamically updating the subarray sums.
Steps to Solve the Problem
- Initialization:
- Define
maxendto track the sum of the current subarray. Initialize it to0. - Define
resto store the maximum subarray sum found so far. Start withnums[0](the first element) because even if the array has only one element, that’s the result.
- Define
- Iterate Over the Array:
- Loop through each element in
nums.
- Loop through each element in
- Update the Current Subarray Sum:
- Add the current element (
nums[i]) tomaxend.
- Add the current element (
- Update the Maximum Subarray Sum:
- If
maxendis greater thanres, updaterestomaxend.
- If
- Reset the Current Subarray Sum if Needed:
- If
maxendbecomes negative, reset it to0. A negative sum will not contribute positively to a larger subarray sum.
- If
- Return the Result:
- At the end of the loop, return
resas the maximum sum of a contiguous subarray.
- At the end of the loop, return
7. Search in Rotated Sorted Array
Problem: Search for a target in a rotated sorted array. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Solution: This code solves the problem of searching for a target value in a rotated sorted array. It uses a modified Binary Search approach to account for the rotated structure of the array.
Steps to Solve the Problem
- Initialize Variables:
s(start) is set to the beginning of the array (0).e(end) is set to the last index of the array (nums.size() - 1).
- Binary Search Loop:
- While
s <= e, calculate the middle index,m = (s + e) / 2.
- While
- Check if the Middle Element is the Target:
- If
nums[m] == target, returnmas the index where the target is found.
- If
- Determine the Sorted Half:
- Check which side of the array (left or right of
m) is sorted:- Left half is sorted: If
nums[s] <= nums[m]. - Right half is sorted: Otherwise (
nums[s] > nums[m]).
- Left half is sorted: If
- Check which side of the array (left or right of
- Search in the Relevant Half:
- For the sorted half:
- Check if the target lies within the range of the sorted portion.
- Adjust
soreaccordingly to narrow the search.
- For the sorted half:
- Handle Equal Elements (Edge Case):
- If
nums[s] == nums[m], incrementsto avoid an infinite loop (handles duplicate elements).
- If
- Target Not Found:
- If the loop ends without finding the target, return
-1.
- If the loop ends without finding the target, return
8. Trapping Rainwater
Problem: Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Solution: This problem aims to calculate the total water that can be trapped between the heights of the bars. The solution uses a pre-computation approach with two auxiliary arrays, left and right, to track the maximum height to the left and right of each bar.
Steps to Solve the Problem
- Handle Edge Case:
- If the input array
heightis empty (n == 0), return0as no water can be trapped.
- If the input array
- Pre-compute Maximum Heights on the Left:
- Create an array
leftwhere:left[i]stores the maximum height from the left up to indexi.
- Initialize
left[0] = height[0]. - For each index
i(from 1 to n−1), compute: - left[i]=max(left[i−1],height[i]).
- Create an array
- Pre-compute Maximum Heights on the Right:
- Create an array
rightwhere:right[i]stores the maximum height from the right up to indexi.
- Initialize
right[n-1] = height[n-1]. - For each index
i(from n−2 to 0), compute: - right[i]=max(right[i+1],height[i])
- Create an array
- Calculate Trapped Water:
- For each bar at index
i, calculate the water trapped as: trapped_Water[i]=min(left[i],right[i])−height[i] - Accumulate the trapped water in the variable
trapped_Water.
- For each bar at index
- Return the Total Water:
- After iterating through all indices, return the total
trapped_Water.
- After iterating through all indices, return the total
9. Two Sum
Problem: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Solution: The goal is to find two indices ‘i’ and ‘j’ such that nums[i]+nums[j]=target. This solution uses a nested loop to check all possible pairs in the array.
Steps to Solve the Problem
- Initialize Variables:
- Create an empty vector
ansto store the indices of the two numbers that sum up to the target. - Get the size of the input array
numsin variablen.
- Create an empty vector
- Nested Loops to Check Pairs:
- Use the outer loop with index
ito iterate through each element ofnumsfrom 0 to n−1. - Use the inner loop with index
jstarting from i+1 to iterate through the elements afteri. - For each pair (i,j), check if:
- nums[i]+nums[j]==target.
- Use the outer loop with index
- Store the Indices:
- If the condition nums[i]+nums[j]==target is satisfied:
- Add
iandjto theansvector.
- Add
- If the condition nums[i]+nums[j]==target is satisfied:
- Return the Result:
- After iterating through all possible pairs, return the
ansvector containing the indices of the two numbers.
- After iterating through all possible pairs, return the
10. Valid Parentheses
Problem: Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
Solution: To solve this, we’ll use a stack data structure. The stack helps us keep track of the opening brackets, and when we encounter a closing bracket, we can easily check if it matches the most recent opening bracket.
Steps to Solve the Problem
- Initialize a Stack:
- Create a stack
ansto keep track of the opening brackets.
- Create a stack
- Iterate Over the String:
- Loop through each character
chin the strings.
- Loop through each character
- Handle Opening Brackets:
- If the current character is an opening bracket (‘(‘, ‘{‘, or ‘[‘), push it onto the stack.
- Handle Closing Brackets:
- If the current character is a closing bracket (‘)’, ‘}’, or ‘]’):
- Check if the stack is empty. If it is, it means there’s no matching opening bracket, so return
false. - If the stack is not empty, check the top element of the stack:
- If the top matches the current closing bracket (i.e., if
chis ‘)’ and the top is ‘(‘, orchis ‘}’ and the top is ‘{‘, etc.), pop the stack. - Otherwise, return
falsebecause the brackets do not match.
- If the top matches the current closing bracket (i.e., if
- Check if the stack is empty. If it is, it means there’s no matching opening bracket, so return
- If the current character is a closing bracket (‘)’, ‘}’, or ‘]’):
- Final Check:
- After iterating through the entire string, if the stack is empty, it means all opening brackets had matching closing brackets, so return
true. - If the stack is not empty, return
false, indicating there are unmatched opening brackets left.
- After iterating through the entire string, if the stack is empty, it means all opening brackets had matching closing brackets, so return
These are the some important Dsa Questions that you atleast once face in your tech Interview or exam. You can also try to solve these questions with various different approaches, but also keep a rough flow chart of each approaches and solution that you can explain to someone in details.
Stay connected for more content like this.
Happy Coding!
Leave a Reply