Tag Archives: Data Structure Interview Questions

Replace every element with the next greatest

Given an array of integers, replace every element with the next greatest element on the right side in the array. Replace last element with 0 as there no element on the right side of it. eg. if the array is {6, 7, 4, 3, 5, 2}, output {7, 5, 5, 5, 2, 0} Method 1 Read More →

Rotate an array by d elements

Problem: Write a program that will rotate a given array of size n by d elements. eg: 1 2 3 4 5 6 7 and d = 3 Output : 4 5 6 7 1 2 3 Method 1: For rotating the array by d elements, first rotate it by 1. Move a[1] to a[0], Read More →

Find row with maximum number of 1s in sorted matrix

Problem: You are given a MxN matrix with each row sorted. Matrix is having only 0′s and 1′s. You have to find row wotth maximum number of 1′s. eg. matrix given: 000111 001111 011111 000011 111111 // row with max number of 1′s Method 1: Brute force approach Traverse the matrix row wise and count Read More →

Find the number occurring odd number of times in an array

You are given an array of integers. All the numbers in array occurs even number of times except the one which occurs odd number of time. You have to find the number in O(N) time and constant space. For eg. 1,4,6,7,3,1,4,7,3,1,6 (given array) Output: 1 Solution: Take bitwise XOR of all the elements. We will Read More →

Print nodes at K distance from root in binary tree

In a binary tree, given a root and a number K. You have to find the all nodes at distance K from given root node. For example in a given tree, if K =2 then Output should be 4,5,6 if k = 1 then Output should be 2,3 Time complexity: O(N) as we have to Read More →

Print Pairs with the given difference in sorted array

Given a sorted array and a number k. print all pairs in the array with difference between them is k. Solution 1: Using Hash Map Create a hashmap and then traverse the array. Use array elements as hash keys and enter them in hashmap. Traverse the array again and look for value k + arr[i] Read More →

Length of Longest substring without repeating characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1. Solution: When you have found a repeated character (let’s say at index j), Read More →

Kth largest or smallest element in an array

Write an C program to find kth largest element in an array. Elements in array are not sorted. example, if given array is [1, 3, 12, 19, 13, 2, 15] and you are asked for the 3rd largest element i.e., k = 3 then your program should print 13. Method 1 Use sorting. Return first Read More →