0% found this document useful (0 votes)
18 views17 pages

DSA Questions

The document contains a series of coding problems categorized into easy, medium, and hard levels, each accompanied by a story, problem statement, input/output examples, and solutions in C++. It covers various data structures and algorithms, including binary search, linked lists, and dynamic programming. Each problem is designed to test different programming skills and concepts.
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)
18 views17 pages

DSA Questions

The document contains a series of coding problems categorized into easy, medium, and hard levels, each accompanied by a story, problem statement, input/output examples, and solutions in C++. It covers various data structures and algorithms, including binary search, linked lists, and dynamic programming. Each problem is designed to test different programming skills and concepts.
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
You are on page 1/ 17

EASY LEVEL QUESTIONS

1.Element Existence in Sorted Array

Story: A librarian has arranged books by their ID numbers in ascending order. She wants to
quickly check if a book with a specific ID is present.

Problem: Given a sorted array and a target value, determine if the target exists using binary
search.

Input: [1, 3, 5, 7, 9], target = 5

Output: true

Explanation: 5 is located at index 2 in the array.

Solution:

bool binarySearch(vector<int>& nums, int target) {

int l = 0, r = nums.size() - 1;

while (l <= r) {

int mid = l + (r - l) / 2;

if (nums[mid] == target) return true;

else if (nums[mid] < target) l = mid + 1;

else r = mid - 1;

return false;

}
2. Balanced Parentheses

Story: You're a magician and your spells require perfectly matching symbols (like parentheses).
One missing symbol, and the spell fails!

Problem: Check if a given string of parentheses is balanced.Input contains ‘(‘ and ‘)’
parenteses.

Input: "(()())"

Output: true

Explanation: Each '(' has a matching ')'.

Solution:

bool isValid(string s) {

stack<char> st;

for (char c : s) {

if (c == '(') st.push(c);

else if (c == ')') {

if (st.empty()) return false;

st.pop();

return st.empty();

"([)]"
3.Count Nodes in Linked List

Story: Think of a train with connected coaches. You’re asked to count how many coaches
(nodes) the train has.

Problem: Count the number of nodes in a singly linked list.

Input: 1 -> 2 -> 3 -> 4

Output: 4

Explanation: There are four nodes in total.

Solution:

int countNodes(ListNode* head) {


int count = 0;
while (head) {
count++;
head = head->next;
}
return count;
}
4.Two Sum Problem (Hashing)

Story: Imagine you're at a store with a gift card worth a certain amount. You want to pick two
items whose total cost exactly matches the card value.

Problem: Given an array of integers and a target, return the indices of two numbers such that
they add up to the target.

●​ Input: [2, 7, 11, 15], target = 9


●​ Output: [0, 1]
●​ Explanation: nums[0] + nums[1] = 2 + 7 = 9

Solution:

vector<int> twoSum(vector<int>& nums, int target) {


unordered_map<int, int> mp;

for (int i = 0; i < nums.size(); i++) {

int complement = target - nums[i];


if (mp.count(complement)) {
return {mp[complement], i};
}
mp[nums[i]] = i;
}
return {};
}
5.Find Second Maximum Element (Array)

●​ Story: After finding the biggest marble, the child wants to find the second biggest marble
to keep as a backup in case he loses his favorite.

●​ Problem: Given an array of integers, find the second maximum distinct element.
●​ Input: [3, 5, 1, 8, 2]
●​ Output: 5
●​ Explanation: 8 is the maximum, 5 is the second highest.

Solution:

int findSecondMax(vector<int>& nums) {


int max1 = INT_MIN, max2 = INT_MIN;
for (int num : nums) {
if (num > max1) {
max2 = max1;
max1 = num;
} else if (num > max2 && num != max1) {
max2 = num;
}
}
return max2;
}
MEDIUM LEVEL QUESTIONS

1.Rotate Array by k Steps (Array)

Story: A group of dancers stand in a circle. After each song, they all move k steps to the
right. What’s the new order after the move?

Problem: Rotate the array to the right by k steps.

Input: nums = [1, 2, 3, 4, 5, 6, 7], k = 3

Output: [5, 6, 7, 1, 2, 3, 4]

Explanation: After 3 right shifts, the last 3 elements come to the front.

Solution:

void rotate(vector<int>& nums, int k) {


int n = nums.size();
k = k % n;
reverse(nums.begin(), nums.end());
reverse(nums.begin(), nums.begin() + k);
reverse(nums.begin() + k, nums.end());
}
2. Binary Search on Rotated Array

Story: A treasure map is split and rotated accidentally. You need to find a specific
number in the rotated map.

Problem: Search target in rotated sorted array.

Input: [4, 5, 6, 7, 0, 1, 2], target = 0

Output: 4

Explanation: Element 0 is found at index 4

Solution:

int search(vector<int>& nums, int target) {

int left = 0, right = nums.size() - 1;

while (left <= right) {


int mid = (left + right) / 2;
if (nums[mid] == target) return mid;

if (nums[left] <= nums[mid]) {


if (nums[left] <= target && target < nums[mid])
right = mid - 1;
else
left = mid + 1;
} else {
if (nums[mid] < target && target <= nums[right])
left = mid + 1;
else
right = mid - 1;
}
}
return -1;
}
3.Next Greater Element

Story: Each warrior wants to know who the next stronger warrior is to their right. Help
each warrior find their successor.

Problem: For each element, find the next greater element to its right.

Input: [4, 5, 2, 10]

Output: [5, 10, 10, -1]

Explanation: For 4 → 5, for 5 → 10, for 2 → 10, for 10 → no greater

Solution:

vector<int> nextGreaterElements(vector<int>& nums) {

vector<int> res(nums.size(), -1);


stack<int> st;
for (int i = 0; i < nums.size(); i++) {
while (!st.empty() && nums[i] > nums[st.top()]) {
res[st.top()] = nums[i];
st.pop();
}
st.push(i);
}
return res;
}
4.Reverse a Linked List

Story: You’re organizing a line of people for a performance but want to reverse the
order for a surprise ending.

Problem: Reverse a singly linked list.

Input: 1 → 2 → 3 → 4

Output: 4 → 3 → 2 → 1

Explanation: Each node's pointer is flipped.

Solution:

ListNode* reverseList(ListNode* head) {

ListNode* prev = NULL;

while (head) {
ListNode* next = head->next;

head->next = prev;
prev = head;
head = next;

}
return prev;
}
5.Daily Temperatures (Stack)

Story: A weather station records daily temperatures. For each day, you want to
know how many days you have to wait until a warmer temperature comes.

Problem: Given a list of daily temperatures, return a list such that for each day,
you tell in how many days a warmer temperature will occur. If not, return 0.

Input: temperatures = [73, 74, 75, 71, 69, 72, 76, 73]

Output: [1, 1, 4, 2, 1, 1, 0, 0]

Explanation: For each day, we find the next day with a higher temperature.

Solution:

vector<int> dailyTemperatures(vector<int>& temperatures) {

int n = temperatures.size();
vector<int> res(n, 0);
stack<int> st;

for (int i = 0; i < n; ++i) {

while (!st.empty() && temperatures[i] > temperatures[st.top()]) {


int prev = st.top();
st.pop();
res[prev] = i - prev;
}
st.push(i);
}

return res;
}
HARD LEVEL QUESTIONS

1. Word Break

Story: You have a dictionary and a sentence without spaces. Can you break it into
valid words?

Problem: Given a string and a word dictionary, return true if it can be segmented
into a space-separated sequence of one or more dictionary words.

Input: s = "leetcode", wordDict = ["leet", "code"]

Output: true

bool wordBreak(string s, unordered_set<string>& wordDict) {

unordered_map<string, bool> memo;


return dfs(s, wordDict, memo);

bool dfs(string s, unordered_set<string>& wordDict, unordered_map<string, bool>& memo) {

if (s.empty()) return true;


if (memo.count(s)) return memo[s];

for (int i = 1; i <= s.size(); ++i) {


if (wordDict.count(s.substr(0, i)) && dfs(s.substr(i), wordDict, memo))
return memo[s] = true;
}

return memo[s] = false;


}
2.Largest Rectangle in Histogram

Story: Imagine each bar in a bar chart represents the height of a building. Find the
largest area rectangle you can make using these bars.

Problem: Given an array of bar heights, find the largest rectangular area in the
histogram.

Input: [2, 1, 5, 6, 2, 3]

Output: 10

Solution:

int largestRectangleArea(vector<int>& heights) {

stack<int> st;

heights.push_back(0);

int maxArea = 0;

for (int i = 0; i < heights.size(); ++i) {

while (!st.empty() && heights[i] < heights[st.top()]) {

int h = heights[st.top()]; st.pop();

int w = st.empty() ? i : i - st.top() - 1;

maxArea = max(maxArea, h * w);

st.push(i);

return maxArea;

}
3.Trapping Rain Water

Story: After a rainstorm, valleys between buildings fill with water. Given the heights of
the buildings, calculate how much water is trapped.​

Problem: Given n non-negative integers representing the elevation map where the width
of each bar is 1, compute how much water it can trap after raining.​

Input: [0,1,0,2,1,0,1,3,2,1,2,1]​

Output: 6​

Explanation: Water is trapped at valleys formed between taller bars

Solution:

int trap(vector<int>& height) {

int left = 0, right = height.size() - 1;


int leftMax = 0, rightMax = 0, water = 0;

while (left < right) {

if (height[left] < height[right]) {


height[left] >= leftMax ? (leftMax = height[left]) : water += (leftMax - height[left]);
left++;
} else {
height[right] >= rightMax ? (rightMax = height[right]) : water += (rightMax - height[right]);
right--;
}

}
return water;
}
4. Detect and Remove Loop in Linked List

Story: A group of people are passing a secret note in a circle. Someone notices that the
note never stops circulating—can you identify where the cycle starts and remove it to
stop the endless loop?​

Problem: Given a linked list, detect if a loop exists, and if it does, remove the loop.​

Input: 1 → 2 → 3 → 4 → 5 → 3 (cycle back to node 3)​

Output: The linked list should become 1 → 2 → 3 → 4 → 5

Solution:
void removeLoop(ListNode* head) {
ListNode *slow = head, *fast = head;

while (fast && fast->next) {


slow = slow->next;
fast = fast->next->next;
if (slow == fast) break;
}

if (!fast || !fast->next) return;

slow = head;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}

while (fast->next != slow)


fast = fast->next;

fast->next = nullptr;
}
5.N-Queens Problem

Story: You’re organizing a royal chess tournament. Each queen must be placed
such that no two threaten each other. Find all possible arrangements on an N×N
board.​

Problem: Place N queens on an N×N chessboard such that no two queens attack
each other. Return all distinct solutions.​

Input: n = 4

[".Q..",

"...Q",

"Q...",

"..Q."],

["..Q.",

"Q...",

"...Q",

".Q.."]

]
Solution:

bool isSafe(int row, int col, vector<string>& board, int n) {

for (int i = 0; i < row; ++i)

if (board[i][col] == 'Q') return false;

for (int i = row-1, j = col-1; i >= 0 && j >= 0; --i, --j)

if (board[i][j] == 'Q') return false;

for (int i = row-1, j = col+1; i >= 0 && j < n; --i, ++j)

if (board[i][j] == 'Q') return false;

return true;

void solve(int row, vector<string>& board, vector<vector<string>>& result, int n) {

if (row == n) {

result.push_back(board);

return;

for (int col = 0; col < n; ++col) {

if (isSafe(row, col, board, n)) {

board[row][col] = 'Q';

solve(row + 1, board, result, n);


board[row][col] = '.';

vector<vector<string>> solveNQueens(int n) {

vector<vector<string>> result;

vector<string> board(n, string(n, '.'));

solve(0, board, result, n);

return result;

You might also like