{"id":2630,"date":"2021-04-06T07:49:56","date_gmt":"2021-04-06T07:49:56","guid":{"rendered":"https:\/\/www.prepbytes.com\/blog\/?p=2630"},"modified":"2022-03-10T18:59:52","modified_gmt":"2022-03-10T18:59:52","slug":"top-20-algorithm-interview-questions","status":"publish","type":"post","link":"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/","title":{"rendered":"Top 20 algorithm interview questions"},"content":{"rendered":"<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1646202519327-Articles_362-1.png\" alt=\"\" \/><\/p>\n<ol>\n<li>Given an array of integers, find the indices of two numbers that sum up to the given target. For example \u2013<br \/>\nArr[] = {1, 2, 4 -3, 7}, and target = 6, we exactly one such occurrence return the indices of those elements.<br \/>\nAns. The idea here is to use two pointer techniques after sorting the array. These two pointers work because we need to return two indices or find two sum elements whose sum is equal to the target and can be increased or decreased by changing the pointers. I and j are the two indices from left and right of the array respectively.<\/p>\n<pre><code>arri+ arrj&gt; target; j--;\narri+ arrj&lt; target; i++;\narri+ arrj== target; return i,j;<\/code><\/pre>\n<pre><code>#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\nvector&lt;int&gt; twoSum(vector&lt;int&gt;&amp; nums, int target) {\n    vector&lt;pair&lt;int,int&gt; &gt; v;\n    for(int i = 0;i&lt;nums.size();i++)\n        v.push_back(make_pair(nums[i],i));\n    sort(v.begin(),v.end());\n   int i = 0, j = v.size()-1 ;\n    while(i&lt;j){\n        if(v[i].first + v[j].first &gt; target)\n            j--;\n        if(v[i].first + v[j].first &lt; target)\n            i++;\n        if(v[i].first + v[j].first == target)\n            return {v[i].second,v[j].second};\n    }\n    return {};\n}\nint main() {\n\/\/ your code goes here\nint n;\ncin&gt;&gt;n;\nvector&lt;int&gt; v(n);\nfor(int i  =0;i&lt;n;i++)\n    cin&gt;&gt;v[i];\nint target;\ncin&gt;&gt;target;\nvector&lt;int&gt; ans = twoSum(v,target);\nfor(auto ele:ans)\n    cout&lt;&lt;ele&lt;&lt;&quot; &quot;;\nreturn 0;\n}\nOutput: 1 2 for given input.<\/code><\/pre>\n<\/li>\n<li>Given an array of integers find the indices of three numbers that sum up to the given target. Find all those unique tuples.<br \/>\nArr[] = {1, 2, 4 -3, 7}, and target = 3<br \/>\nAns. The idea here is to use two pointer techniques after sorting the array. The only difference is we need to set a new target such for every element in the outer loop. Suppose every element in outer loop is arr[i] then new target= target-arr[i]. Then we can simply apply the same two pointer technique. These two pointers works because we need to return two indices or find two sum elements whose sum is equal to the target and can be increased or decreased by changing the pointers. I and j are the two indices from left and right of the array respectively.<br \/>\nfor every arr[k], newtarget=target-arr[k]<\/p>\n<pre><code>arri+ arrj&gt; newtarget; j--;\narri+ arrj&lt; newtarget; i++;\narri+ arrj== newtarget; return arri,arrj,arr[k];<\/code><\/pre>\n<p>Ans.<\/p>\n<pre><code>#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\nvector&lt;vector&lt;int&gt;&gt; threeSum(vector&lt;int&gt;&amp; nums,int target) {\n    if(nums.size()&lt;3)return {};\n    set&lt;vector&lt;int&gt; &gt; sv;\n    vector&lt;vector&lt;int&gt; &gt; ans;\n    sort(nums.begin(),nums.end());\n    for(int  i = 0;i&lt;nums.size()-2;i++){\n        int newt = target - nums[i];            \n        int j = i+1,k = nums.size()-1;\n        while(j&lt;k){\n            if(nums[j] + nums[k] &gt; newt)\n                k--;\n            if(nums[j] + nums[k] &lt; newt)\n                j++;\n            if(nums[j] + nums[k] == newt &amp;&amp; j!=k)\n            { \n                sv.insert({nums[i],nums[j],nums[k]});\n                \/\/ if(j!=nums.size()-1 &amp;&amp; k!=0 &amp;&amp; j&lt;k)\n                j++;k--;                    \n            }\n        }            \n    }\n    for(auto x : sv){\n        ans.push_back(x);\n    }\n    return ans;\n}\nint main() {\n\/\/ your code goes here\nint n;\ncin&gt;&gt;n;\nvector&lt;int&gt; v(n);\nfor(int i  =0;i&lt;n;i++)\n    cin&gt;&gt;v[i];\nint target;\ncin&gt;&gt;target;\nvector&lt;vector&lt;int&gt;&gt; ans = threeSum(v,target);\nfor(auto ele:ans)\n    {\n        cout&lt;&lt;ele[0]&lt;&lt;&quot; &quot;&lt;&lt;ele[1]&lt;&lt;&quot; &quot;&lt;&lt;ele[2]&lt;&lt;endl;\n    }\nreturn 0;\n}<\/code><\/pre>\n<\/li>\n<li>\n<p>Given an array of integers find the indices of four numbers that sum up to given target. Find all those unique 4 elements.<br \/>\nArr[] = {1, 2, 4 -3, 7}, and target = 4<br \/>\nOutput: -3 1 2 4<br \/>\nAns. <\/p>\n<pre><code>#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\nvector&lt;vector&lt;int&gt;&gt; foursum(vector&lt;int&gt;&amp; nums, int target) {\n    if(nums.size()&lt;4)return {};\n    sort(nums.begin(),nums.end());\n    vector&lt;vector&lt;int&gt; &gt; v;\n    set&lt;vector&lt;int&gt; &gt; sv;\n    for(int i = 0;i&lt;nums.size()-3;i++){\n        int target1 = target - nums[i]; \n        for(int j = i+1;j&lt;nums.size()-2;j++){\n            int newt = target1 - nums[j];\n            int k = j+1,l=nums.size()-1;\n\n            while(k&lt;l){\n                if(nums[k] + nums[l] == newt)\n                    {\n                    sv.insert({nums[i],nums[j],nums[k],nums[l]});\n                    k++;l--;\n                    }\n                if(nums[k] + nums[l] &gt; newt)\n                    l--;\n                if(nums[k] + nums[l] &lt; newt)\n                    k++;\n\n            }\n        }\n    }\n    for(auto x : sv)\n        v.push_back(x);\n\n    return v;\n}\nint main() {\n\/\/ your code goes here\nint n;\ncin&gt;&gt;n;\nvector&lt;int&gt; v(n);\nfor(int i  =0;i&lt;n;i++)\n    cin&gt;&gt;v[i];\nint target;\ncin&gt;&gt;target;\nvector&lt;vector&lt;int&gt;&gt; ans = foursum(v,target);\nfor(auto ele:ans)\n    {\n        cout&lt;&lt;ele[0]&lt;&lt;&quot; &quot;&lt;&lt;ele[1]&lt;&lt;&quot; &quot;&lt;&lt;ele[2]&lt;&lt;&quot; &quot;&lt;&lt;ele[3]&lt;&lt;endl;\n    }\nreturn 0;\n}<\/code><\/pre>\n<\/li>\n<li>\n<p>Given an array find the maximum sum of the subarray.<br \/>\nArr = [-2 -2 4 -1 -2 1 5 -3]<br \/>\nOutput: 4-1-2+1+5 = 7<br \/>\nAns.<\/p>\n<pre><code>#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\nint kadane(int arr[], int n)\n{\nint globalmax= 0;\nint localmax= 0;\n\nfor (int i = 0; i &lt; n; i++)\n{\n    localmax= localmax+ arr[i];\n    localmax= max(localmax, 0);\n    globalmax= max(globalmax, localmax);\n}\n\nreturn globalmax;\n}\nint main() {\nint n;\ncin&gt;&gt;n;\nint arr[n];\nfor(int i = 0;i&lt;n;i++)\ncin&gt;&gt;arr[i];\ncout&lt;&lt;kadane(arr,n);\nreturn 0;\n}<\/code><\/pre>\n<\/li>\n<li>\n<p>You are given the ability to shop as much as you can from a store. But you have limited capacity bag which can only hold weight up to w. There N items in the store. You have to take maximum valued items such that you can take those items home.<br \/>\nInput: 4(number of items)<br \/>\n1 2 4 5(weights of each item)<br \/>\n5 4 8 6 (values of each item)<br \/>\nOutput: 13 =(5 + 8)<br \/>\nAns.<\/p>\n<pre><code>#include&lt;iostream&gt;\nusing namespace std;\nint k(int* wt, int* val, int n, int w,int** dp)\n{\nif(n==0||w==0)return 0;\n if(dp[n][w]!=-1)return dp[n][w];\n\nif(wt[n-1]&lt;=w)\n{\n    int ans = max(val[n-1]+k(wt,val,n-1,w-wt[n-1],dp),k(wt,val,n-1,w,dp));\n    dp[n][w] = ans;\n    return ans;\n}\nif(wt[n-1]&gt;w)\n{\n    int ans = k(wt,val,n-1,w,dp);\n    dp[n][w] = ans;\n    return ans;\n}\n}\nint knapsack(int* weights, int* values, int n, int maxWeight){\nint N = n;\nint w = maxWeight;\nint** dp = new int*[N+1];\nfor(int i = 0;i&lt;n+1;i++)\n    dp[i] = new int[w+1];\nfor(int i = 0;i&lt;n+1;i++)\n    for(int j = 0;j&lt;w+1;j++)\n        dp[i][j] = -1;\n\nreturn k(weights,values,N,w,dp);\n}\nint main(){\nint n;\ncin &gt;&gt; n;\nint* weights = new int[n];\nint* values = new int[n];\nfor(int i = 0; i &lt; n; i++){\ncin &gt;&gt; weights[i];\n}\nfor(int i = 0; i &lt; n; i++){\ncin &gt;&gt; values[i];\n}\nint maxWeight;\ncin &gt;&gt; maxWeight;\ncout &lt;&lt; knapsack(weights, values, n, maxWeight);\n}<\/code><\/pre>\n<\/li>\n<li>\n<p>Given two strings write a program to find if one string is the substring of the other or not.<br \/>\nInput: WelcomeBack<br \/>\nCome<br \/>\nOutput: 1<br \/>\nAns. <\/p>\n<pre><code>#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\nint* lpsarray(string p)\n{\nint len = p.length();\nint* lps = new int[len];\n\nlps[0] = 0;\nint i = 1;\nint j = 0;\nwhile(i&lt;len)\n{\n    if(p[i]==p[j]){\n        lps[i] = j+1;\n        j++;\n        i++;\n    }\n    else\n    {\n        if(j!=0){\n            j = lps[j-1];\n        }\n        else\n        {\n            lps[i] = 0;\n            i++;\n        }\n    }\n}\nreturn lps;\n}\nbool isMatching(string str,string pattern)\n{\nint* lps = lpsarray(pattern);\nint lenstr = str.length();\nint lenpattern  = pattern.length();\n\nint i = 0;\nint j = 0;\n\nwhile(i&lt;lenstr &amp;&amp; j&lt;lenpattern)\n{\n    if(str[i]==pattern[j])\n    {\n        i++;\n        j++;\n    }\n    else\n    {\n        if(j!=0){\n            j = lps[j-1];\n        }\n        else\n        {\n            i++;\n        }\n    }\n}\nif(j==lenpattern)return true;\n\nreturn false;\n}\nint position(string str, string pattern)\n{\nint* lps = lpsarray(pattern);\nint lenstr = str.length();\nint lenpattern  = pattern.length();\n\nint i = 0;\nint j = 0;\n\nwhile(i&lt;lenstr &amp;&amp; j&lt;lenpattern)\n{\n    if(str[i]==pattern[j])\n    {\n        i++;\n        j++;\n    }\n    else\n    {\n        if(j!=0){\n            j = lps[j-1];\n        }\n        else\n        {\n            i++;\n        }\n    }\n}\nif(j==lenpattern)return (i - lenpattern);\n\nreturn -1;\n}\nint main()\n{\nstring str;\nstring pattern;\ncin&gt;&gt;str&gt;&gt;pattern;\n\ncout&lt;&lt;isMatching(str,pattern)&lt;&lt;endl;\n return 0;\n}<\/code><\/pre>\n<\/li>\n<li>You are given a grid and you have to start from a position of top left. Each cells in the grid contains either health or poison. Health is denoted by positive integers while poison os denoted by negative integers. Whenever you come to a cell your health either increases or decreases depending upon the cell value. Now you have to reach the bottom right cell of the grid and if at any cell your health drops to zero you will loose. You have to find the minimum amount of health to start with so that you can reach the right most down cell.<\/li>\n<\/ol>\n<pre><code>Input: 1(test cases)  3 4 (dimensions of the grid)\n0 -2 -3 1\n-1 4 0 -2\n1 -2 -3 0\nOutput: 2<\/code><\/pre>\n<p>Ans. <\/p>\n<pre><code>#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\nint min(int a,int b)\n{\n    if(a&lt;b)return a;\n    else return b;\n}\nint main()\n{\n    int t;\n    cin&gt;&gt;t;\n    while(t--)\n    {\n        int r,c;\n        cin&gt;&gt;r&gt;&gt;c;\n        int a[r][c];\n        for(int i = 0;i&lt;r;i++)\n            for(int j = 0;j&lt;c;j++)\n                cin&gt;&gt;a[i][j];\n         int m = r,n=c;\n     int hp[m+1][n+1];\n    for(int i = 0;i&lt;m+1;i++)\n        for(int j = 0;j&lt;n+1;j++)\n            hp[i][j] = INT_MAX;\n    hp[m][n-1]=1;\n    hp[m-1][n]=1;\n    for(int i = m-1;i&gt;=0;i--)\n        for(int j = n-1;j&gt;=0;j--)\n        {\n            int need = min(hp[i+1][j],hp[i][j+1])-a[i][j];\n            if(need&lt;=0) hp[i][j]=1;\n            else\n                hp[i][j]=need;\n        }\n        cout&lt;&lt;hp[0][0]&lt;&lt;endl;\n    }\n    return 0;\n}<\/code><\/pre>\n<ol start=\"8\">\n<li>Given a non-empty array of integers arr, every element appears twice except for one. Find that single element. Implement this in linear time and no extra space.<br \/>\nArr[] = {2,2,3}<br \/>\nAns. <\/p>\n<pre><code>#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\nint singleNumber(vector&lt;int&gt;&amp; nums) {\n    int xor1 = nums[0];        \n    for(int i = 1;i&lt;nums.size();i++)\n        xor1 = xor1^nums[i];        \n    return xor1;\n}\nint main() {\n\/\/ your code goes here\nint n;\ncin&gt;&gt;n;\nvector&lt;int&gt; v(n);\nfor(int i = 0;i&lt;n;i++)\n    cin&gt;&gt;v[i];\ncout&lt;&lt;singleNumber(v)&lt;&lt;endl;    \nreturn 0;\n}<\/code><\/pre>\n<\/li>\n<li>Given a list of nodes from 0 to n-1 and respective edges you have to find the shortest distance between the source node (0) to every other node connected to it. The graph is undirected.<\/li>\n<\/ol>\n<pre><code>Input: 4(number of nodes) 4(number of edges)\n 0 1\n0 3\n1 2\n2 3\nEdge list\nOutput:\n0 1 3 2 (distance of each node from 0)<\/code><\/pre>\n<p>Ans.<\/p>\n<pre><code>#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\nstruct Graph {\n    int V;\n    int E;\n    int** Adj;\n};\nstruct Graph *createAdjMatrix(int V,int E) {\n    struct Graph* G = new Graph;\n    G-&gt;V = V;\n    G-&gt;E = E;\n    G-&gt;Adj = new int*[G-&gt;V];\n    for(int i = 0;i&lt;G-&gt;V;i++)\n    {\n        G-&gt;Adj[i] = new int[G-&gt;V];\n        for(int j = 0;j&lt;G-&gt;V;j++)\n            G-&gt;Adj[i][j] = 0;\n    }\n    for(int i = 0;i&lt;G-&gt;E;i++)\n    {\n        int u,v;\n        cin&gt;&gt;u&gt;&gt;v;\n\n        G-&gt;Adj[u][v] = 1;\n        G-&gt;Adj[v][u] = 1;\n    }\n    return G;    \n}\nvoid BFS(struct Graph* G,int u,bool* visited){\n    queue&lt;int&gt; q;\n    q.push(u);\n    visited[u] = true;\n\n    while(!q.empty()){\n        int currentVertex = q.front();\n        q.pop();\n        cout&lt;&lt;currentVertex&lt;&lt;&quot; &quot;;        \n        for(int i = 0;i&lt;G-&gt;V;i++)\n        {\n            if(i==currentVertex)\n                continue;\n            if(!visited[i] &amp;&amp; G-&gt;Adj[currentVertex][i])\n            {\n                q.push(i);\n                visited[i] = true;\n            }\n        }\n    }\n}\nvoid BFSutil(struct Graph* G)\n{\n    bool* visited = new bool[G-&gt;V];\n    for(int i = 0;i&lt;G-&gt;V;i++)\n        visited[i] = false;    \n    for(int i = 0;i&lt;G-&gt;V;i++)\n        if(!visited[i])\n            BFS(G,i,visited);    \n}\nint main() {\n    int V, E;\n    cin &gt;&gt; V &gt;&gt; E;\n    struct Graph *G = createAdjMatrix(V,E);  \n    BFSutil(G);\n  return 0;\n}<\/code><\/pre>\n<ol start=\"10\">\n<li>You are again given an edge list and this time also given the weights of each edge and now again you have to find the shortest distance of the source node (0) to all other nodes.\n<pre><code>Node Node Weight\n0   1   2\n0   4   5\n1   3   9\n1   5   1\n2   3   1\n2   4   3   \n3   5   2\n3   4   7\nOutput: (node  distance) \n0 0\n1 2 \n2 6\n3 5\n4 5\n5 3<\/code><\/pre>\n<p>Ans. <\/p>\n<pre><code>#include&lt;bits\/stdc++.h&gt;\nusing namespace std;\nclass Graph{\nunordered_map&lt;int,list&lt;pair&lt;int,int&gt;&gt;&gt; m;\npublic:\nvoid addEdge(int x,int y,int w,bool bidir = true){\n    m[x].push_back(make_pair(y,w));\n    if(bidir)\n    m[y].push_back(make_pair(x,w));\n}\nvoid dijkstra(int src){\n    map&lt;int,int&gt; dist;\n    set&lt;pair&lt;int,int&gt;&gt; s;\n    for(auto node : m){\n        \/\/marking all nodes dist as infinity\n        dist[node.first] = INT_MAX;\n    }\n    dist[src] = 0;\n    \/\/ for(auto ele : dist){\n    \/\/     cout&lt;&lt;ele.first&lt;&lt;&quot; &quot;&lt;&lt;ele.second&lt;&lt;endl;\n    \/\/ }\n    s.insert(make_pair(0,src));\n    while(!s.empty()){\n        auto distpair = *s.begin();\n        s.erase(s.begin());\n        int node = distpair.second;\n        int nodedist = distpair.first;\n        for(auto nbr : m[node]){\n            if(nodedist + nbr.second &lt; dist[nbr.first])\n            {\n                \/\/update the distance\n                auto f = s.find(make_pair(dist[nbr.first],nbr.first));\n                dist[nbr.first] = nodedist + nbr.second;\n                if(f!=s.end())\n                    s.erase(f);\n                s.insert(make_pair(dist[nbr.first],nbr.first));\n            }\n        }\n    }\n    for(auto ele : dist){\n        cout&lt;&lt;ele.first&lt;&lt;&quot; &quot;&lt;&lt;ele.second&lt;&lt;endl;\n    }\n}\n};\nint main(){\nGraph g;\ng.addEdge(0,1,2);\ng.addEdge(0,4,5);\ng.addEdge(1,3,9);\ng.addEdge(1,5,1);\ng.addEdge(2,3,1);\ng.addEdge(2,4,3);\ng.addEdge(2,5,4);\ng.addEdge(3,5,2);\ng.addEdge(3,4,7);\ng.dijkstra(0);\nreturn 0;\n}<\/code><\/pre>\n<\/li>\n<li>You are given a set of edges and nodes. These nodes are numbered from 0 to n-1, where n is the number of nodes. Again, we are given edges between these nodes and this time they are directed and you have to find the order of nodes in which each node will come such that no other nodes on which current node depends will not come faster. E.g., suppose there is an edge between 3-&gt;4 this means for getting node 4, node 3 has to be before 4.<\/li>\n<\/ol>\n<pre><code>Input: 8(nodes)\n9(edges)\n\n0 3\n0 5\n1 4\n2 4\n2 5\n4 3\n4 6\n4 7\n5 7\nEdge list<\/code><\/pre>\n<p>Ans.<\/p>\n<pre><code>#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\nstruct Graph {\n    int V;\n    int E;\n    int** Adj;\n};\nstruct Graph *createAdjMatrix(int V,int E) {\n    struct Graph* G = new Graph;\n    G-&gt;V = V;\n    G-&gt;E = E;\n    G-&gt;Adj = new int*[G-&gt;V];\n    for(int i = 0;i&lt;G-&gt;V;i++)\n    {\n        G-&gt;Adj[i] = new int[G-&gt;V];\n        for(int j = 0;j&lt;G-&gt;V;j++)\n            G-&gt;Adj[i][j] = 0;\n    }\n    for(int i = 0;i&lt;G-&gt;E;i++)\n    {\n        int u,v;\n        cin&gt;&gt;u&gt;&gt;v;\n\n        G-&gt;Adj[u][v] = 1;\n       \/\/ G-&gt;Adj[v][u] = 1;\n    }\n    return G;    \n}\nvector&lt;int&gt; BFS(struct Graph* G,int u,bool* visited){\n    priority_queue&lt;int&gt; q;\n    vector&lt;int&gt; topoVector;\n    vector&lt;int&gt; indegree(G-&gt;V,0);\n    for(int i = 0;i&lt;G-&gt;V;i++){\n        for(int j = 0;j&lt;G-&gt;V;j++)\n        {\n            if(G-&gt;Adj[i][j])\n                indegree[j]++;\n        }}\n    for(int i = 0;i&lt;G-&gt;V;i++)\n        if(indegree[i]==0)\n            q.push(i);\n\n    while(!q.empty()){\n        int currentVertex = q.top();\n        q.pop();\n        visited[currentVertex] = true;\n        topoVector.push_back(currentVertex);\n\n        for(int i = 0;i&lt;G-&gt;V;i++)\n        {\n            if(i==currentVertex)\n                continue;\n            if(!visited[i] &amp;&amp; G-&gt;Adj[currentVertex][i])\n            {\n                indegree[i] = indegree[i] - 1;\n                if(indegree[i]==0)\n                    q.push(i);\n                \/\/visited[i] = true;\n            }\n        }\n    }\n\n    return topoVector;\n}\n\nvector&lt;int&gt; BFSutil(struct Graph* G)\n{\n    bool* visited = new bool[G-&gt;V];\n    for(int i = 0;i&lt;G-&gt;V;i++)\n        visited[i] = false;\n    vector&lt;int&gt; v;\n            v = BFS(G,0,visited);\n    return v;\n}\nint main() {\n    int V, E;\n    cin &gt;&gt; V &gt;&gt; E;\n    struct Graph *G = createAdjMatrix(V,E);\n\n   vector&lt;int&gt; v = BFSutil(G);\n    for(auto i:v)\n        cout&lt;&lt;i&lt;&lt;&quot; &quot;;\n\n  return 0;\n}<\/code><\/pre>\n<ol start=\"12\">\n<li>Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index.\n<pre><code>Input: arr = {4 3 1 0 5}, \nOutput: 1 , start at position 4 and then to 5(last position)<\/code><\/pre>\n<p>Ans.<\/p>\n<pre><code>#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\nbool canJump(vector&lt;int&gt;&amp; nums) {\n    if(nums.size() == 0)\n        return true;        \n    int midx = 0;\n    for(int i = 0; i &lt;= midx; ++ i){\n        midx = max(midx, i + nums[i]);\n        if(midx &gt;= nums.size()-1)\n            return true;\n    }\n    return midx &gt;= nums.size()-1;\n}\nint main() {\nvector&lt;int&gt; num1={4,3,1,0,5};\ncout&lt;&lt;canJump(num1);\nreturn 0;\n}<\/code><\/pre>\n<\/li>\n<li>\n<p>Given an array of integers where every element appears twice except two elements which appear once. You have to return these two elements.<br \/>\nArr[] = [1 2 3 1 2 5]<br \/>\nOutput: 3 5<br \/>\nAns. <\/p>\n<pre><code>#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\nvector&lt;int&gt; solve(vector&lt;int&gt;&amp; nums) {\n   int diff = accumulate(nums.begin(), nums.end(), 0, bit_xor&lt;int&gt;());\n    \/\/ Get its last set bit\n    diff &amp;= -diff;\n\n    \/\/ Pass 2 :\n    vector&lt;int&gt; rets = {0, 0}; \/\/ this vector stores the two numbers we will return\n    for (int num : nums)\n    {\n        if ((num &amp; diff) == 0) \/\/ the bit is not set\n        {\n            rets[0] ^= num;\n        }\n        else \/\/ the bit is set\n        {\n            rets[1] ^= num;\n        }\n    }\n    return rets;\n}\nint main() {\nint n;\ncin&gt;&gt;n;\nvector&lt;int&gt; arr(n);\nfor(int i = 0;i&lt;n;i++)\ncin&gt;&gt;arr[i];\nvector&lt;int&gt; ans = solve(arr);\nfor(auto ele : ans)\ncout&lt;&lt;ele[0]&lt;&lt;&quot; &quot;&lt;&lt;ele[1]&lt;&lt;endl;\nreturn 0;\n}<\/code><\/pre>\n<\/li>\n<li>You must have played chess, don\u2019t worry if you haven\u2019t. A knight is a piece of chess which can move in some specific directions given by the arrows. You have to find out whether your Knight can travel to all cell in the grid or not. If it can travel to all cells then return true else false.<br \/>\n![](link to image)<br \/>\nInput: N = 8<br \/>\nOutput: 1 (knight can travel to all of the 64 cells)<br \/>\nAns.<\/p>\n<pre><code>#include &lt;bits\/stdc++.h&gt;\n#define N 8\nusing namespace std;\nint mat[N][N];\n\/\/simple travelling that works for square matrix\nint row[N] = {2, 1, -1, -2, -2, -1, 1, 2 };\nint col[N] = {1, 2, 2, 1, -1, -2, -2, -1 };\nbool isValid(int r,int c){\nreturn (r&gt;=0 &amp;&amp; c&gt;=0 &amp;&amp; r&lt;N &amp;&amp; c&lt;N &amp;&amp; mat[r][c] == -1);\n}\nbool knight_tour(int r,int c,int move){\nif(move == N*N)\n    return true; \/\/ base condition\nint move_x, move_y;\nfor(int k = 0;k&lt;N;k++){\n    move_x = r + row[k];\n    move_y = c + col[k];\n    if(isValid(move_x,move_y)){\n        mat[move_x][move_y] = move + 1; \/\/storing the move number in matrix\n        if(knight_tour(move_x,move_y,move + 1) == 1)return true;\n        else mat[move_x][move_y] = -1;\/\/backtracking\n    }\n}\nreturn false;\n}\nint main() {\n\/\/ your code goes here\nmemset(mat,-1,sizeof(mat));\nmat[0][0] = 1;\nif(knight_tour(0,0,1)){\/\/calling recur function\n\/\/print the path matrix\nfor(int i = 0;i&lt;N;i++)\n    {\n        for(int j = 0;j&lt;N;j++)\n            cout&lt;&lt;mat[i][j]&lt;&lt;&quot;  &quot;;\n        cout&lt;&lt;endl;\n    }\n}\nelse cout&lt;&lt;&quot;Not possible\\n&quot;;\nreturn 0;\n}<\/code><\/pre>\n<\/li>\n<li>Do you know about LRU cache? Well, a LRU cache is basically a memory or data structure which stores the recently used objects for faster access next time. It implements two functions get and put, where get function returns the recently used in the cache and put inserts the new recently used object in the cache.<br \/>\nget(int key) Return the value of the key if the key exists, otherwise return -1.<br \/>\nput(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.<br \/>\nAns. <\/p>\n<pre><code>int size;\nlist&lt;pair&lt;int,int&gt;&gt; l;    unordered_map&lt;int,list&lt;pair&lt;int,int&gt;&gt;::iterator&gt; m;\n\/\/basics of this class\nWe will implement the above two functions \u2013\nint get(int key) {\n    if(m.find(key)!=m.end()){\n        auto it = m.find(key);\n        int val = it-&gt;second-&gt;second;\n        if(it-&gt;second == l.begin())return val;\n        l.erase(m[key]);            l.push_front(make_pair(key,val));\n        m[key] = l.begin();\n        return val;\n    }\n    return -1;\n}    \nvoid put(int key, int value) {\n    \/\/if the key is presetn int the list or not\n    \/\/if the key is present\n    if(m.find(key)!=m.end()){\n        auto location = m[key];\n        l.erase(location);\n        m.erase(key);\n    }\n    \/\/if the key is not present and size is full\n    if(m.size() == size){\n        int delkey = l.back().first;\n        l.pop_back();\n        m.erase(delkey);\n    }\n    l.push_front(make_pair(key,value));\n    m[key] = l.begin();\n    \/\/printlist();cout&lt;&lt;endl;\n}<\/code><\/pre>\n<\/li>\n<li>In this problem we are given a binary string, simply a string of 0 and 1 and we are asked to reduce this number (which can be formed from this binary string) to 1 by following operations \u2013\n<ul>\n<li>If the number is even then divide it by 2<\/li>\n<li>If the number is odd then add 1 to it<br \/>\nInput: 101<br \/>\n101(5) -&gt; 110(6) -&gt; 011(3) -&gt;100(4) -&gt; 010(2) -&gt; 001(1)<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<p>Output: 5<br \/>\nReturn the number of steps if this is possible.<br \/>\nAns. <\/p>\n<pre><code> #include &lt;bits\/stdc++.h&gt;\nusing namespace std;\nint steps(string s){\n  int step = 0;\n  while(s.size()&gt;1){\n    if(s.back() == &#039;0&#039;)\/\/even\n    {\n      s.pop_back();\n      step++;\n      continue;\n    }\n    bool chk = false; \/\/if we at all get any 0\n    for(int i = s.size()-1;i&gt;=0;i--){\n      if(s[i] == &#039;0&#039;){\n        s[i] = &#039;1&#039;;\n        chk = true;\n        break;\n      }\n      s[i] = &#039;0&#039;;\n    }\n    if(!chk)s=&quot;1&quot;+s;\n    step++;  \n  }\n    return step;\n}\nint main()\n{\n  \/\/write your code here\n  string s;\n  cin&gt;&gt;s;\n  cout&lt;&lt;steps(s)&lt;&lt;endl;\n  return 0;\n}<\/code><\/pre>\n<ol start=\"17\">\n<li>Implement a merge sort algorithm.<br \/>\nAns.<\/p>\n<pre><code>#include&lt;bits\/stdc++.h&gt;\nusing namespace std;\n\/\/merges two sorted arrays\nvoid merge(int a[],int l,int m,int r){\nint n1 = m-l+1;\nint n2 = r-m;\nint L[n1],R[n2];\nfor(int i=0;i&lt;n1;i++){\n    L[i] = a[l+i];\n}\nfor(int i=0;i&lt;n2;i++){\n    R[i] = a[m+i+1];\n}\nint i=0,j=0,k=l;\nwhile(i&lt;n1 &amp;&amp; j&lt;n2){\n    if(L[i]&lt;=R[j]){\n        a[k++]=L[i++];\n    }\n    else{\n        a[k++]=R[j++];\n    }\n}\nwhile(i&lt;n1){\n    a[k++]=L[i++];\n}\nwhile(j&lt;n2){\n    a[k++]=R[j++];\n}\n}\n\/\/recursively performs merge sort\nvoid merge_sort(int a[],int l,int r){\nif(l &lt; r){\n    int m = l+(r-l)\/2;\n    merge_sort(a,l,m);\n    merge_sort(a,m+1,r);\n    merge(a,l,m,r);\n}\n}\n\/\/wrapper for merge_sort\nvoid mergeSort(int ar_size,int a[]){\nmerge_sort(a,0,ar_size-1);}\nint main() {\nint ar_size = 5, i;\nint a[5] = {1, 5, 4, 3, 2};\nmergeSort(ar_size, a);\nfor(i=0; i&lt;ar_size; i++){\n    cout&lt;&lt;a[i]&lt;&lt;&quot; \\n&quot;[i==ar_size-1];\n}\nreturn 0;\n}\nOutput: 1 2 3 4 5<\/code><\/pre>\n<\/li>\n<li>Implement quicksort algorithm.<br \/>\nAns. <\/p>\n<pre><code>#include&lt;iostream&gt;\nusing namespace std;\n\/\/ Partition\nint partition(int *array, int l, int r){\nint pivot = array[r];\nint i = l-1; \/\/ place for swapping\nfor(int j = l; j &lt;= r-1; j++){\n    if(array[j] &lt;= pivot){\n        i++;\n        swap(array[i], array[j]);\n    }\n}\nswap(array[i+1], array[r]);\nreturn (i+1);\n}\n\/\/ Random pivot\nint partition_random_pivot(int *array, int l, int r){\nsrand(time(NULL));\nint random = l + rand()%(r - l);\nswap(array[random], array[r]);\nreturn partition(array, l, r);\n}\nint quick_sort(int *array, int l, int r){\nif(l &lt; r){   \/\/ base case\n    int pi = partition_random_pivot(array, l, r);  \/\/ returns index of pivot\n    quick_sort(array, l, pi-1);\n    quick_sort(array, pi+1, r);\n}\n}\nint main(int argc, char const *argv[]){\nint N;\ncout &lt;&lt; &quot;Enter the size of array:&quot;;\ncin &gt;&gt; N;\nint A[N];\ncout &lt;&lt; &quot;Enter the array elements:&quot;;\nfor(int i = 0; i &lt; N; i++) cin &gt;&gt; A[i];\nquick_sort(A, 0, N-1);\ncout &lt;&lt; &quot;Sorted array is: &quot;;\nfor(int i = 0; i &lt; N; i++) cout &lt;&lt; A[i] &lt;&lt; &quot; &quot;;\ncout &lt;&lt; endl;\nreturn 0;\n}<\/code><\/pre>\n<\/li>\n<li>You are given an array which contains the price of stocks for each day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).<br \/>\nPrice [] = [7 1 5 3 6 4]<br \/>\nOutput: 7, which we can get from buying on day 2 and sell on day 3.<br \/>\nAns. <\/p>\n<pre><code>#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\nint maxprofit(vector&lt;int&gt;&amp; prices) {\n    int profit=0;\n    for(int i=1;i&lt;prices.size();i++){\n        if((prices[i]-prices[i-1])&gt;0){\n            profit+=prices[i]-prices[i-1];\n        }\n    }\n    return profit;\n}\nint main() {\n\/\/ your code goes here\nint n;\ncin&gt;&gt;n;\nvector&lt;int&gt; prices(n);\nfor(int i = 0;i&lt;n;i++)\n    cin&gt;&gt;prices[i];\ncout&lt;&lt;maxprofit(prices);\nreturn 0;\n}<\/code><\/pre>\n<\/li>\n<li>Given an array of balloons which are painted with a number on it. You are asked to burst balloon such that your score increases by arr[left]<em>arr[i]<\/em>arr[right]. Left = i-1, right =i+1, after each burst the left and right balloons become adjacent. Find the maximum score by bursting balloons.<br \/>\nArr[] = [4 1 5 10]<br \/>\nOutput: 270<br \/>\nAns.<\/p>\n<pre><code>#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\nint maxScore(vector&lt;int&gt;&amp; nums) {\n    if(!nums.size())\n        return 0;\n    int n = nums.size();\n    nums.insert(nums.begin(), 1);\n    nums.insert(nums.end(), 1);\n    vector&lt;vector&lt;int&gt;&gt; dp(nums.size(), vector&lt;int&gt;(nums.size(), 0));\n    for(int len = 1; len &lt;= n; ++ len ){\n        for(int start = 1; start &lt;= n - len + 1; ++ start){\n            int end = start + len - 1;\n            for(int i = start; i &lt;= end; ++ i){\n                dp[start][end] = max(dp[start][end], dp[start][i - 1] + dp[i + 1][end] + nums[start - 1]*nums[i]*nums[end + 1]);\n            }\n        }\n    }        \n    return dp[1][n];\n}\nint main() {\n\/\/ your code goes here\nint n;\ncin&gt;&gt;n;\nvector&lt;int&gt; arr(n);\nfor(int i = 0;i&lt;n;i++)\n    cin&gt;&gt;arr[i];\ncout&lt;&lt;maxScore(prices);\nreturn 0;\n}<\/code><\/pre>\n<\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>Given an array of integers, find the indices of two numbers that sum up to the given target. For example \u2013 Arr[] = {1, 2, 4 -3, 7}, and target = 6, we exactly one such occurrence return the indices of those elements. Ans. The idea here is to use two pointer techniques after sorting [&hellip;]<\/p>\n","protected":false},"author":52,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[147],"tags":[],"class_list":["post-2630","post","type-post","status-publish","format-standard","hentry","category-interview-questions"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.8 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Top 20 algorithm interview questions | Interview Questions | PrepBytes<\/title>\n<meta name=\"description\" content=\"The idea here is to use two pointer techniques after sorting the array. The only difference is we need to set a new target such for every element in the outer loop.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Top 20 algorithm interview questions | Interview Questions | PrepBytes\" \/>\n<meta property=\"og:description\" content=\"The idea here is to use two pointer techniques after sorting the array. The only difference is we need to set a new target such for every element in the outer loop.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/\" \/>\n<meta property=\"og:site_name\" content=\"PrepBytes Blog\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/prepbytes0211\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-04-06T07:49:56+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-03-10T18:59:52+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1646202519327-Articles_362-1.png\" \/>\n<meta name=\"author\" content=\"Prepbytes\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Prepbytes\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"22 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/\"},\"author\":{\"name\":\"Prepbytes\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/3f7dc4ae851791d5947a7f99df363d5e\"},\"headline\":\"Top 20 algorithm interview questions\",\"datePublished\":\"2021-04-06T07:49:56+00:00\",\"dateModified\":\"2022-03-10T18:59:52+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/\"},\"wordCount\":1120,\"commentCount\":0,\"publisher\":{\"@id\":\"http:\/\/43.205.93.38\/#organization\"},\"image\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1646202519327-Articles_362-1.png\",\"articleSection\":[\"Interview Questions\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/\",\"url\":\"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/\",\"name\":\"Top 20 algorithm interview questions | Interview Questions | PrepBytes\",\"isPartOf\":{\"@id\":\"http:\/\/43.205.93.38\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1646202519327-Articles_362-1.png\",\"datePublished\":\"2021-04-06T07:49:56+00:00\",\"dateModified\":\"2022-03-10T18:59:52+00:00\",\"description\":\"The idea here is to use two pointer techniques after sorting the array. The only difference is we need to set a new target such for every element in the outer loop.\",\"breadcrumb\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/#primaryimage\",\"url\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1646202519327-Articles_362-1.png\",\"contentUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1646202519327-Articles_362-1.png\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"http:\/\/43.205.93.38\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Interview Questions\",\"item\":\"https:\/\/prepbytes.com\/blog\/category\/interview-questions\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Top 20 algorithm interview questions\"}]},{\"@type\":\"WebSite\",\"@id\":\"http:\/\/43.205.93.38\/#website\",\"url\":\"http:\/\/43.205.93.38\/\",\"name\":\"PrepBytes Blog\",\"description\":\"ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING\",\"publisher\":{\"@id\":\"http:\/\/43.205.93.38\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"http:\/\/43.205.93.38\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"http:\/\/43.205.93.38\/#organization\",\"name\":\"Prepbytes\",\"url\":\"http:\/\/43.205.93.38\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp\",\"contentUrl\":\"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp\",\"width\":160,\"height\":160,\"caption\":\"Prepbytes\"},\"image\":{\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/prepbytes0211\/\",\"https:\/\/www.instagram.com\/prepbytes\/\",\"https:\/\/www.linkedin.com\/company\/prepbytes\/\",\"https:\/\/www.youtube.com\/channel\/UC0xGnHDrjUM1pDEK2Ka5imA\"]},{\"@type\":\"Person\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/3f7dc4ae851791d5947a7f99df363d5e\",\"name\":\"Prepbytes\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/232042cd1a1ea0e982c96d2a2ec93fb70a8e864e00784491231e7bfe5a9e06b5?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/232042cd1a1ea0e982c96d2a2ec93fb70a8e864e00784491231e7bfe5a9e06b5?s=96&d=mm&r=g\",\"caption\":\"Prepbytes\"},\"url\":\"https:\/\/prepbytes.com\/blog\/author\/gourav-jaincollegedekho-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Top 20 algorithm interview questions | Interview Questions | PrepBytes","description":"The idea here is to use two pointer techniques after sorting the array. The only difference is we need to set a new target such for every element in the outer loop.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/","og_locale":"en_US","og_type":"article","og_title":"Top 20 algorithm interview questions | Interview Questions | PrepBytes","og_description":"The idea here is to use two pointer techniques after sorting the array. The only difference is we need to set a new target such for every element in the outer loop.","og_url":"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/","og_site_name":"PrepBytes Blog","article_publisher":"https:\/\/www.facebook.com\/prepbytes0211\/","article_published_time":"2021-04-06T07:49:56+00:00","article_modified_time":"2022-03-10T18:59:52+00:00","og_image":[{"url":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1646202519327-Articles_362-1.png","type":"","width":"","height":""}],"author":"Prepbytes","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Prepbytes","Est. reading time":"22 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/#article","isPartOf":{"@id":"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/"},"author":{"name":"Prepbytes","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/3f7dc4ae851791d5947a7f99df363d5e"},"headline":"Top 20 algorithm interview questions","datePublished":"2021-04-06T07:49:56+00:00","dateModified":"2022-03-10T18:59:52+00:00","mainEntityOfPage":{"@id":"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/"},"wordCount":1120,"commentCount":0,"publisher":{"@id":"http:\/\/43.205.93.38\/#organization"},"image":{"@id":"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/#primaryimage"},"thumbnailUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1646202519327-Articles_362-1.png","articleSection":["Interview Questions"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/","url":"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/","name":"Top 20 algorithm interview questions | Interview Questions | PrepBytes","isPartOf":{"@id":"http:\/\/43.205.93.38\/#website"},"primaryImageOfPage":{"@id":"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/#primaryimage"},"image":{"@id":"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/#primaryimage"},"thumbnailUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1646202519327-Articles_362-1.png","datePublished":"2021-04-06T07:49:56+00:00","dateModified":"2022-03-10T18:59:52+00:00","description":"The idea here is to use two pointer techniques after sorting the array. The only difference is we need to set a new target such for every element in the outer loop.","breadcrumb":{"@id":"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/#primaryimage","url":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1646202519327-Articles_362-1.png","contentUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1646202519327-Articles_362-1.png"},{"@type":"BreadcrumbList","@id":"https:\/\/prepbytes.com\/blog\/top-20-algorithm-interview-questions\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"http:\/\/43.205.93.38\/"},{"@type":"ListItem","position":2,"name":"Interview Questions","item":"https:\/\/prepbytes.com\/blog\/category\/interview-questions\/"},{"@type":"ListItem","position":3,"name":"Top 20 algorithm interview questions"}]},{"@type":"WebSite","@id":"http:\/\/43.205.93.38\/#website","url":"http:\/\/43.205.93.38\/","name":"PrepBytes Blog","description":"ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING","publisher":{"@id":"http:\/\/43.205.93.38\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"http:\/\/43.205.93.38\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"http:\/\/43.205.93.38\/#organization","name":"Prepbytes","url":"http:\/\/43.205.93.38\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/","url":"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp","contentUrl":"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp","width":160,"height":160,"caption":"Prepbytes"},"image":{"@id":"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/prepbytes0211\/","https:\/\/www.instagram.com\/prepbytes\/","https:\/\/www.linkedin.com\/company\/prepbytes\/","https:\/\/www.youtube.com\/channel\/UC0xGnHDrjUM1pDEK2Ka5imA"]},{"@type":"Person","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/3f7dc4ae851791d5947a7f99df363d5e","name":"Prepbytes","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/232042cd1a1ea0e982c96d2a2ec93fb70a8e864e00784491231e7bfe5a9e06b5?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/232042cd1a1ea0e982c96d2a2ec93fb70a8e864e00784491231e7bfe5a9e06b5?s=96&d=mm&r=g","caption":"Prepbytes"},"url":"https:\/\/prepbytes.com\/blog\/author\/gourav-jaincollegedekho-com\/"}]}},"_links":{"self":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/2630","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/users\/52"}],"replies":[{"embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/comments?post=2630"}],"version-history":[{"count":3,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/2630\/revisions"}],"predecessor-version":[{"id":7950,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/2630\/revisions\/7950"}],"wp:attachment":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/media?parent=2630"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/categories?post=2630"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/tags?post=2630"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}