Solving Dsa Interview Questions

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

SOLVING DSA

INTERVIEW QUESTIONS
VRITIKA NAIK







SUPPLEMENTS – What you need to know!

WARM UP – Revising Basics for Solving

EXERCISE – The Actual Questions

ASSESSMENT – Score yourself

REPLENISHMENT – The Final Tips


Number
Graphs
Theory

Binary Search String and Array


Tree Manipulation

Dynamic Search and


Programming Sorts

Linked List
• DFS and BFS Traversals
• Dijkstra’s Algorithm for Shortest Path
• Prim’s and Kruskal’s For Minimum Spanning
Tree
• 0-1 Knapsack Problem
• Subset Sum Problem
• Longest Common Subsequence
• Longest Increasing Subsequence
• Modular Exponentiation
• Sum of Bit Differences among All Pairs
1. Binary Search
2. Search an element in a sorted and rotated
array
3. Bubble Sort
4. Selection Sort
5. Insertion Sort
6. Merge Sort
7. Heap Sort (Binary Heap)
8. Quick Sort
9. Topological Sort
Time to freshen up and refresh concepts!
Go to Kahoot.it and enter the code.
Happy Quizzing!!!
Given a string s representing a roman numeral.
Convert s into an integer.
X = 10
XII = 12
XL = 40

ASKED IN AMAZON, MICROSOFT, FACEBOOK


1.Split the Roman Numeral string into Roman Symbols
(character).
2.Convert each symbol of Roman Numerals into the
value it represents.
3.Take symbol one by one from starting from index 0:
1. If current value of symbol is greater than or equal
to the value of next symbol, then add this value
to the running total.
2. else subtract this value by adding the value of
next symbol to the running total.
Example
Input: "VII"
Output: 7
Explanation: V+I+I = 5+1+1 = 7

Input: “IV"
Output: 4
Explanation: V-I = 5-1 = 4
int romanToDecimal(string& str)
{
int res = 0;
int value(char r)
for (int i = 0; i < str.length(); i++) {
{
// Getting value of symbol s[i]
if (r == 'I')
int s1 = value(str[i]);
return 1;
if (i + 1 < str.length()) {
if (r == 'V')
// Getting value of symbol s[i+1]
return 5;
int s2 = value(str[i + 1]);
if (r == 'X')
if (s1 >= s2) {
return 10;
res = res + s1;
if (r == 'L')
}
return 50;
else {
if (r == 'C')
res = res + s2 - s1;
return 100;
i++;
if (r == 'D')
}
return 500;
}
if (r == 'M')
else {
return 1000;
res = res + s1;
return -1;
}
}
}
return res;
}
Given an unsorted array of integers, sort the
array into a wave like array. An array ‘arr[0..n-1]’
is sorted in wave form if arr[0] >= arr[1] <=
arr[2] >= arr[3] <= arr[4] >= …..

Examples:
Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80}
Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80}
OR {20, 5, 10, 2, 80, 6, 100, 3}
OR any other array that is in wave form

ASKED IN ADOBE, MICROSOFT, FACEBOOK


void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}

• Sort the array


void sortInWave(int arr[], int n)
• Swap elements {
// Sort the input array
sort(arr, arr+n);

// Swap adjacent elements


for (int i=0; i<n-1; i += 2)
swap(&arr[i], &arr[i+1]);
}
Given, an array arr[]of size n having non-negative
integers h1, h2, ..., hn, where each represents a point at
coordinate (i, hi). There are n vertical lines drawn such
that the two endpoints of line i are at (i, hi) and (i, 0).
Write a program to find two lines, which together with
the x-axis forms a container, such that the container
contains the most water.
Note: You may not slant the container and n is at least 2.
Example:
Input: arr[] = [1, 2, 4, 3]
Output: 4
Explanation: The area of water between the lines of
height 2 and 3 is maximum and equal to 2*2 = 4.

ASKED IN AMAZON, GOOGLE, FACEBOOK, ADOBE


• Create a nested loop, the outer int maxArea(int A[], int len)
loop traverses the array from 0 to {
end (index of this loop is i).
int area = 0;
• The inner loop traverses the for(int i = 0; i < len; i++)
array from i + 1 to end
{
(index of this loop is j).
for(int j = i + 1; j < len; j++)
• Find the water that can be
{
contained in the container
with height of boundaries as // Calculating the max area
array[i] and array[j], i.e area area = max(area, min(A[j],
= (j – i)* min(array[i],array[j]), A[i]) * (j - i));
if this area is greater than
current maximum, update the
current maximum }
}
• Print the current maximum.
return area;
}
Given two strings str1 and str2 and below operations that can
performed on str1. Find minimum number of edits (operations) required
to convert ‘str1’ into ‘str2’. Insert, Remove, Replace are all of equal cost.
Examples:
Input: str1 = "geek", str2 = "gesek"
Output: 1
We can convert str1 into str2 by inserting a 's’.

Input: str1 = "cat", str2 = "cut"


Output: 1
We can convert str1 into str2 by replacing 'a' with 'u’.

Input: str1 = "sunday", str2 = "saturday"


Output: 3
Last three and first characters are same. We basically need to convert
"un" to "atur". This can be done using below three operations. Replace 'n'
with 'r', insert t, insert a

ASKED IN AMAZON, GOOGLE, MICROSOFT


int min(int x, int y, int z)
{ return min(min(x, y), z); }

int editDist(string str1, string str2, int m, int n)


{
The idea is process all characters one by
one staring from either from left or right // If first string is empty, the only option is to
sides of both strings. // insert all characters of second string into first
Let us traverse from right corner, there if (m == 0)
are two possibilities for every pair of return n;
character being traversed.
• m: Length of str1 (first string) n: Length // If second string is empty, the only option is to remove
of str2 (second string) // all characters of first string
if (n == 0)
• If last characters of two strings are
same, nothing much to do. Ignore last return m;
characters and get count for remaining
strings. So we recur for lengths m-1 and // If last characters of two strings are same, nothing much to
n-1. // do. Ignore last characters and get count for remaining
strings.
• Else (If last characters are not same),
if (str1[m - 1] == str2[n - 1])
we consider all operations on ‘str1’,
return editDist(str1, str2, m - 1, n - 1);
consider all three operations on last
character of first string, recursively
compute minimum cost for all three // If last characters are not same, consider all three
operations and take minimum of three // operations on last character of first string, recursively
values. // compute minimum cost for all three operations and take
• Insert: Recur for m and n-1 // minimum of three values.
return 1 + min(editDist(str1, str2, m, n - 1), // Insert
• Remove: Recur for m-1 and n
editDist(str1, str2, m - 1, n), // Remove
• Replace: Recur for m-1 and n-1 editDist(str1, str2, m - 1, n - 1) // Replace
);
}
Given an input string s and a dictionary of words wordDict, write a program
to determine if s can be divided into a space-separated sequence of one or
more words that are present in the wordDict.
Problem Note
•Assume that both s and wordDict are non-empty.
•The same word in the dictionary may be reused multiple times in the
division.
•You may assume the dictionary does not contain duplicate words.
Example 1
Input: s = "AfterAcademy", wordDict = ["After", "Academy"] Output: true
Explanation: Return true because "AfterAcademy" can be segmented as
"After Academy".
Example 2
Input: s = "HardThingAboutHardThings", wordDict = ["Hard", "Things",
"Thing", "About"] Output: true Explanation: Return true because
"HardThingAboutHardThings" can be segmented as "Hard Thing About
Hard Things". Note that you are allowed to reuse a dictionary word.

ASKED IN FACEBOOK, GOOGLE


bool wordBreak(string str)
• Consider each prefix and {
search it in dictionary. int size = str.size();
• If the prefix is present in if (size == 0) return true;
dictionary, we recur for
rest of the string (or // Try all prefixes of lengths
suffix). from 1 to size
• If the recursive call for for (int i=1; i<=size; i++)
suffix returns true, we {
return true, otherwise we if (dictionaryContains(
try next prefix. str.substr(0, i) ) && wordBreak(
• If we have tried all str.substr(i, size-i) ))
prefixes and none of them return true;
resulted in a solution, we }
return false.
return false;
}
Given a square matrix, turn it by 90 degrees in clockwise
direction without using any extra space.

Input:
123
456
789

Output:
741
852
963

Explanation: The given matrix is rotated by 90 degree in


clockwise direction.

ASKED IN AMAZON, FACEBOOK, GOOGLE, ADOBE


void rotation(int arr[N][N])
{
for (int i = 0; i < N; i++)
for (int j = i; j < N; j++)
swap(arr[i][j], arr[j][i]);
int k;
for (int i = 0; i < N; i++)
{
k = N-1;
for (int j = 0; j < k; j++)
{
swap(arr[i][j], arr[i][k]);
k--;
}
}
}
Given n non-negative array of integers arr representing an
elevation map where the width of each bar is 1 unit. Write a
program to compute how much water it can trap after
raining.
The elevation map is represented by array [4, 2, 9, 1, 0, 1,
1, 2]. In this case, 7 units of rain water (green section) are
being trapped.

Example
Input: [4, 2, 9, 1, 0, 1, 1, 2]
Output: 7
Explanation: You can see the above image in which the
input array is drawn as an elevation map. Here, all the
green boxes represent the number of units of water that
can be trapped after raining.

ASKED IN AMAZON, GOOGLE


int maxWater(int arr[], int n)
{

// To store the maximum water that can


be stored
1. Traverse the array from start to int res = 0;
end. for (int i = 1; i < n-1; i++) {
2. For every element, traverse the
array from start to that index // Find the maximum element on its
and find the maximum left
height (a) and traverse the int left = arr[i];
array from the current index to for (int j=0; j<i; j++)
end and find the maximum left = max(left, arr[j]);
height (b).
3. The amount of water that will // Find the maximum element on its
be stored in this column right
is min(a,b) – array[i], add this int right = arr[i];
value to total amount of water for (int j=i+1; j<n; j++)
stored right = max(right, arr[j]);
4. Print the total amount of water
stored. // Update the maximum water
res = res + (min(left, right) - arr[i]);
}

return res;
}
Know Know your Fundamentals

Read Read the question twice and understand it well

Visualize Visualize the Question and draw it

Write Write on Paper

Practice Do Mock Tests

Optimize Don’t be attached to your code. Optimize it.

Beautify Beautify your code

Test Test it for exceptional cases as well.

Code Practice on Competitive Programming Sites


Any Questions?
Connect on Twitter:
@NaikVritika

You might also like