https://algorithms.tutorialhorizon.
com/
Array
Ease
1. Check if array contains all unique or distinct numbers.
Objective: Given an array of integers, write a program to
check if array contains all unique numbers.
Example:
Integer [] arrA = {1, 2, 3, 6, 4, 9, 8}; Output: Array
distinct Integer [] arrB = { 1, 2, 3, 6, 4, 9, 8, 2}; Output:
Array contains duplicates
2. Product of all Unique elements in a given array.
Objective: Given an array of integers which contains
duplicates as well. Write a program to find the product of all
unique elements in the array. This problem is also referred as
find the product of all distinct elements in the array
Example:
[] arrA = {1, 6, 4, 3, 2, 2, 3, 8, 1}; Output : 24 (Unique
elements are: 1, 6, 4, 3, 2, 8)
3. Find first three largest elements in a given array
Objective: Given an array of integers, write an algorithm to
find the first three largest elements in the array.
Example:
Int []a = { 6, 8, 1, 9, 2, 1, 10}; Output: 10, 9, 8 Int []a =
{ 6, 8, 1, 9, 2, 1, 10, 10}; Output: 10, 10,9 Int [] a = {6};
Output: Invalid Input, array size is less than 3
1
4. Find two smallest elements in a given array
Objective: Given an array of integers, write an algorithm to
find the two smallest elements in the array.
Example:
Int[]a ={6, 8, 1, 9, 2, 10}; Output: 1, 2
Int []a={6, 8, 1, 9, 2, 1, 10, 10}; Output: 1, 1
Int [] a ={6}; Output: Invalid Input, array size is less than
2
5. Front and Back Search in an Array
Objective: Given an unsorted array of numbers and a number
‘x’, write a java program to search the number ‘x’ in the
array and return its index else return -1.
Example:
Int [] a = {3, 6, 9, 1, 2, 10} x = 6,
Output: 1 x = 2, Output: 4 x = 7, Output: -1
6. Print all unique elements in a given array
Objective: Given an array of integers which contains
duplicates as well. Write a program to print all unique
elements in the array. This problem is also referred as print
all distinct elements in the array
Example:
[] arrA ={1, 6, 4, 3, 2, 2, 3, 8, 1};
Output: Unique elements are: 1, 6, 4, 3, 2, 8
7. Find first two largest elements in a given array
Objective: Given an array of integers, write an algorithm to
find the first two largest elements in the array.
Example:
2
Int[]a ={6, 8, 1, 9, 2, 1, 10}; Output: 10,9 Int [] a
= {6, 8, 1, 9, 2, 1, 10, 10}; Output: 10,10 Int [] a =
{6};Output: Invalid Input, array size is less than 2
8. Rotate the given array in cycles
Objective: Given an array of integers, write a program to
rotate the array in cyclic manner by one.
Example:
Int a [] = {1, 2, 3, 4, 5} Output: {2, 3, 4, 5, 1}
9. Maximum Difference between two elements in array – Largest Gap
Problem
Objective: Given an array of numbers, write an algorithm to
find the maximum difference between any two elements in the
array.
Example:
Int [] a = {2, 8, 1, 6, 10, 4} Output: Maximum difference= 9
(elements are 1 and 10) Int [] b = {10, 30, 5, 16, 19};
Output:: Maximum difference= 25 (elements are 30 and 5)
10. Separate even and odd integers in a given array
Objective: Given an array which contains even and odd
integers. Write an algorithm to separate even and odd numbers.
Example
int [] arrA = {1,2,3,4,6,8,7,12};
Output: [12, 2, 8, 4, 6, 3, 7, 1]
11. Find three elements in an array that sum to a zero.
Objective: Given an array of integer write an algorithm to
find 3 elements that sum to a zero. In short a+b+c = 0.
Example
int a [] = { 3,-1,-7,-4,-5,9,10};
3
Elements are -4 9 -5
12. Separate 0’s and 1’s in a given array
Objective: Given an array which contains only 0’s and 1’s.
write an algorithm to separate 0’s and 1’s.
Example
int [] arrA = {1,0,1,0,1,1,0,0,0,0,1};
Output: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
12. Separate 0’s and 1’s in a given array
Objective: Given an array which contains only 0’s and 1’s.
write an algorithm to separate 0’s and 1’s.
Example
int [] arrA = {1,0,1,0,1,1,0,0,0,0,1};
Output: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
13. Find three elements in an array that sum to a given value
Objective: Given an array of integer write an algorithm to
find 3 elements that sum to a given number k. In short a+b+c =
k.
Example:
int a [] = {3,1,7,4,5,9,10} , k = 21;Output: Elements are 7 4
10 int a [] = { 3,1,7,4,5,9,10} , k = 55;Output: Did not find
3 elements whose sum is 55
14. Check if array is sorted using recursion
Objective: Given an array of integer write a recursive
solution to check if array is sorted.
Example:
int [] a = {1,2,3,4}; Output: true
int [] a = {1,2,3,4,2};Output: false
4
15. Find the increasing OR decreasing point in an array
Objective: Given an array of integer which is first
increasing then decreasing. Find the element in array from
which point it starts decreasing.
OR
Given an array of integer which is first increasing then
decreasing. Find the maximum element in that array.
Similar Problem: Given an array of integer which is first
decreasing then increasing. Find the element in array from
which point it starts increasing.
OR
Given an array of integer which is first decreasing then
increasing. Find the minimum element in that array.
Example:
int
[]a={1,2,4,6,11,15,19,20,21,31,41,51,55,46,35,24,18,14,13,12,1
1,4,2,1}; output: 55
int [] a = {1,2,4}; //no deceasing element, so last element
will be answer output: 4
int [] a = {4,2,1}; //no deceasing element, so last element
will be answer output: 4
16. Find the only element in array which appears only once
Objective: Given an array of integers, all the elements are
appear twice but one element which appears only once. Write an
algorithm to find that element.
Example:
int [] a = { 1,5,6,2,1,6,4,3,2,5,3};
output: 4
17. Reverse the given Array without using built in function
Objective: Given a array, write an algorithm to reverse the
array.
Example:
int a[] = {1, 2, 3, 4, 5} Output: {5, 4, 3, 2, 1}
5
18. Find the Kth Smallest/Largest Element in an Array
Objective: Given an array of integers. find the
Kth Smallest/largest element in the array.
Example: int[] A = { 1, 2, 10, 20, 40, 32, 44, 51, 6 };
K=4. 4th smallest element in given array: 10
19. Find the Second Largest Element in an Array
Objective: Given an array of integers. find the second largest
element in the array.
Example:
int[] A = { 1, 2, 10, 20, 40, 32, 44, 51, 6 }; Second largest
Element : 44
20. Find a Number occurring odd number of times in a Given array
Objective: Given a array of integers, in which every elements
occurs even number of times except one number which occurs add
number of times. Find out that number.
Example:
int[] A = {1,1,2, 2,3, 3, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7 };
Element appearing add number of times: 5
21. Magic Index – Find Index In Sorted Array Such That A[i] = i.
Objective: Given a sorted array of distinct integers, Find the
Magic index or Fixed point in the array.
Magic Index or Fixed Point: Magic index or a Fixed point in an
array is an index i in the array such that A[i] = i.
Example :
int[]A ={-1, 0, 1, 2, 4,10}; Magic index or fixed point is : 4
22. Construct a Special Triangle from a Given Array
Objective: Given an array of integers such that first level
will print all the elements in the array and from then at each
level number of elements will be one less than the previous
6
level and elements at the level will be the Sum of consecutive
elements in the previous level. Print it in a reverse level.
See Example.
Example:
23. Find The Missing Duplicate in a Given Array.
Objective: – Given an Integer array. Array contains duplicates
of all the numbers in array except one number . Find that
number.
Example :
int []A={2,1,3,5,5,3,2,1,6,7,7,8,8};
Output : Missing duplicate is 6
24. Check if Array is Consecutive Integers
Objective: Given a array of unsorted numbers, check if all the
numbers in the array are consecutive numbers.
Examples:
int [] arrA = {21,24,22,26,23,25}; - True
(All the integers are consecutive from 21 to 26)
int [] arrB = {11,10,12,14,13}; - True
(All the integers are consecutive from 10 to 14)
int [] arrC = {11,10,14,13}; - False
(Integers are not consecutive, 12 is missing)
7
25. Find intersection between Two Sorted Arrays.
Objective: Given two sorted arrays, Find intersection point
between them.
Examples:
int[] a = {1,2,3,6, 8,10 }; int[] b = { 4, 5, 6, 11, 15, 20 };
Output: Intersection point is : 6
26. Find all common numbers in given three sorted arrays.
Objective: Given three sorted(ascending order) arrays of
integers, find out all the common elements in them.
Input: Three sorted arrays.
Output: All the common elements.
Examples :
Array A={1,2,3,4,5,6,7,8,9,10}; Array B = {1,3,5,6,7,8,12};
Array C = {2,3,4,5,8,9}; Common Elements are 3,5,8
27. Minimum number that cannot be formed by any subset of an array
Objective: Given a sorted array of positive integers, find out
the smallest integer which cannot be represented as the sum of
any subset of the array
Input: A Sorted Array
Output: The smallest number which cannot be represented as the
sum of any subset of the given array
Examples :
Array {1,1,3,4,6,7,9} smallest Number : 32
Array {1,1,1,1,1} smallest Number : 6 Array {2,3,6,7}
smallest Number : 1 Array {1,2,6,7,9} smallest Number : 4
28. Find a pair of numbers from an array whose sum equals k
Objective: Write an algorithm to find out whether in a given
array there exists or not two numbers whose sum is exactly
equals to a given number. This problem has been asked in
Amazon and Microsoft interviews.
Input: An array arrA[], A number k
8
Output: True or false based upon we have found any two numbers
in array arrA[] whose sum is equal to k
29. Find a peak element in a Given Array
Objective : In this article we will discuss an algorithm to
Find a peak element in a Given Array. We will see the
recursion techniques to solve this problem.
Peak Element: peak element is the element which is greater
than or equal to both of its neighbors.
Input: Array, arrA[] .
Output: A peak element and its index
Intermediate
1. Find Number of reverse pairs in an array
Objective: Given an array of integers A[],find no of reverse
pairs means no of (i, j) pairs where i < j and A[i]>A[j].
Example:
A[] = {10,3, 4, 2, 5, 7, 9, 11} Output:7 Reversed pairs: (10,
3) (10, 4) (10, 2) (10, 5) (10, 7) (10, 9) (3, 2) (4, 2) = 8
2. Print all subarrays of a given array
Objective: Given an array write an algorithm to print all the
possible sub arrays.
Example:
int [] a = {1, 2, 3}; Output: Possible subarrays –
{1}, {2}, {3}, {1, 2}, {2, 3}, {1, 2, 3}
3. Divide and Conquer – Rearrange array elements in special
order
Objective: Given an array of integers of size 2n, write an
algorithm to arrange them such that first n elements and last
n elements are set up in alternative manner. Say n = 3 and 2n
elements are {x1, x2, x3, y1, y2, y3}, then result should be
{x1, y1, x2, y2, x3, y3}
Example:
9
A [] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10}, n= 5 Output: {1, 2, 3,
4, 5, 6, 7, 8, 9, 10}
4. Find median of two sorted arrays of same size
Objective: Given two sorted arrays of size n. Write an
algorithm to find the median of combined array (merger of both
the given arrays, size = 2n).
What is Median?
The median is the value separating the higher half of a
data sample, a population, or a probability distribution, from
the lower half. For a data set, it may be thought of as the
“middle” value. For example, in the data set {1, 3, 3, 6, 7,
8, 9}, the median is 6, the fourth largest, and also the
fourth smallest, number in the sample. For a continuous
probability distribution, the median is the value such that a
number is equally likely to fall above or below it.
If n is odd then Median (M) = value of ((n + 1)/2)th item
term.
If n is even then Median (M) = value of [(n/2)th item term +
(n/2 + 1)th item term]/2
5. Find the local minima in a given array
Objective: Given an array of integer write an algorithm to
find the local minima.
Local Minima: An element is considered as local minima if it
is less than both of its neighbors (if neighbors exist).
Example:
int [] arrA = {11, 4, 2, 5, 11, 13, 5}; Output: Local Minima
is: 2
int []arrA = {1,2,3,4}; Output: 1
int []arrA = {3}; output: 3
int []arrA = {6,4}; Output: 4
6. Find the two repeating elements in a given array | 6
Approaches
Objective: Given an array of n+2 elements. All elements of the
array are in range 1 to n and all elements occur once except
two numbers which occur twice. Write an algorithm to find the
two repeating numbers.
10
Example:
int [] A = {1,4,5,6,3,2,5,2}; int n = 6;
Output: Two Repeated elements are: 2 and 5
7. Find the element which appears maximum number of times in the
array.
Objective: Given an array of integers, write a algorithm to
find the element which appears maximum number of times in the
array.
Example:
int [] arrA = {4, 1, 5, 2, 1, 5, 9, 8, 6, 5, 3, 2, 4, 7};
Output: Element repeating maximum no of times: 5, maximum
count: 3
8. Find duplicates in an given array in O(n) time and O(1) extra
space.
Objective: Given an array of integers, find out duplicates in
it.
Example:
int[] a ={4,6,2,1,2,5}; Output: Array has duplicates : 2
int a[]={1,6,5,2,3,3,2}; Output: Array has duplicates : 2 , 3
9- Dynamic Programming – Maximum Subarray Problem
Objective: The maximum subarray problem is the task of
finding the contiguous subarray within a one-
dimensional array of numbers which has the largest sum.
Example:
int [] A = {−2, 1, −3, 4, −1, 2, 1, −5, 4};Output: contiguous
subarray with the largest sum is 4, −1, 2, 1, with sum 6.
11
9. Kadane’s Algorithm – Maximum Subarray Problem
Objective: The maximum subarray problem is the task of
finding the contiguous subarray within a one-
dimensional array of numbers which has the largest sum.
Example: int [] A = {−2, 1, −3, 4, −1, 2, 1, −5, 4};
Output: contiguous subarray with the largest sum is 4, −1, 2,
1, with sum 6.
10. Rearrange the Array of Given Range N, such that A[i]=i
Algorithms – Rearrange the Array of Given Range N, such that
A[i]=i.
Objective: Given a array of length N, in which elements are in
the range of 1 to N. All elements may not present in the
array. If element is not present , there will be -1 present in
the array. Rearrange the array such that A[i]=i and if i is
not present, display -1 at that place. See example
Example:
11. Check if Array Contains All Elements Of Some Given Range
Objective: Given an array of unsorted numbers, check if it
contains all elements of some given range.
Examples:
int[] arrA = { 11, 17, 13, 19, 15, 16, 12, 14 };
Range : 12-15 Output: True
12
12. In an Array, find the Contiguous Subarray with Sum to a Given
Value.
Objective: Given an array and an integer, find the Subarray
whose sum is equal to the given integer.
Examples:
int[] arrA = { 25, 12, 14, 22, 19, 15, 10, 23 }; Integer = 55
Output : 55 is found between indexes 2 and 4 And Elements are
: 14 22 19
13. In an Array, find the Smallest Subarray with Sum Greater than
the Given Value
Objective: Given an array and an integer, find the smallest
subarray whose sum is greater than the given integer.
Examples:
arrA[] = { 1, 5, 20, 70, 8} Integer = 97 Output : Min Length =
3 Subarray = [20, 70, 8]
arrA[] = { 1, 10, 3, 40, 18} Integer = 50 Output : Min Length
= 2 Subarray = [40, 18]
14. Find Kth Smallest or Largest element in an Array.
Objective: Find Kth Smallest or Largest element in an Array
Example:
int[] arrA = { 2, 3, 11, 16, 27, 4, 15, 9, 8 };Output: The 4th
smallest element is : 8
15. Given an array arrA[], find the maximum j – i such that
arr[j] > arr[i].
Objective: Given an array arrA[], find the maximum j – i such
that arr[j] > arr[i].
Example:
13
int[] arrA = { 12, 3, 1, 5, 6, 4, 10, 9, 8, 0 }; Output:
Max(j-i) where j>i and A[j]>A[i] is : 7
16. Search an Element in a Rotated Sorted Array
Input: Rotated Sorted Array.
What is Rotated Sorted Array.
A sorted array is rotated around some pivot element. See the
Example Below, array is rotated after 6.
17. Given a Sorted Singly Linked List Array, Convert it into a
Balanced Binary search Tree.
Objective: You have been given a sorted singly List, you need
to convert it into balanced binary search tree.
Why balanced binary tree is important:
You can also create first node as root and insert all other
nodes to the right of the tree because List is in increasing
order but this constructed tree won’t be balanced tree, it wil
be skwed tree and to perform operations on this tree will be
O(n) not O(logn).
Input: An sorted Singly Linked List
Output: Balanced Binary Tree
Example:
14
Singly
18. Sort an Given Array in the order defined by another array
Objective: Given an array of integers, write an algorithm to
sort it according to the order defined by another array.
Input: An Array of Integers
Example:
Input Array : 2 6 9 1 4 4 2 1 10 13 5 7 8
DefinedArray : 1 2 4 6 Output : 1 1 2 2 4 4 6 5 7 8 9 10 13
19. Sort an Array such that the odd numbers appear first followed
by the even numbers . The odd numbers in ascending order and
the even numbers in descending order.
Objective: Given an array of intergers, sort it such that the
odd numbers appear first followed by the even numbers . The
odd numbers in ascending order and the even numbers in
descending order.
Input: An Array of Integers
Example:
Input Array : 1 2 3 4 5 6 7 8 9 10 Output : 1 3 5 7 9 10 8 6 4
2
15
20. Find the number of occurrences of a number in a given sorted
array.
Objective: Given a sorted(ascending order) arrays of integers,
find out the number of occurences of a number in that array
Input: A sorted array arrA[] and a number x.
Output: number of occurrences of ‘x’ in array arrA[].
Examples :
Array - {1,2,2,2,2,2,2,2,3,4,5,5,6} x = 2 Output : No of
Occurrences of number 2 is 7
21. Find the first repeated element in an array by its index
Objective: Given an array of integers, find out the first
repeated element. First repeated element means the element
occurs atleast twice and has smallest index.
Input: An Array
Output: The first repeated element
Examples :
Array {1,1,3,4,6,7,9} first repeated Number : 1 Array
{7,2,2,3,7} first repeated Number : 7 Array
{5,3,3,3,3,3,3,3,4,4,4,5,3} first repeated Number : 5
22. Sorted Array to Binary Search Tree of Minimal Height
Objective: Given a sorted array with unique elements, Create a
binary search tree with minimal height.
Why minimal height is important :
We can do the linear scan to the array and make the first
element as root and insert all other elements into the tree
but in that case tree will be skewed , which means all the
nodes of the tree will be on the one side of the root so the
height of the tree will be equal to the number of elements in
the array. So here our objective is to keep the tree balanced
as much as possible.
What is balanced Tree: A balanced tree is a tree in which
difference between heights of sub-trees of any node in the
tree is not greater than one. To read more about balanced
tree, click here
Input: A one dimensional array
Output: Binary Search Tree of Minimal Height
16
Example:
23. Count All Paths from Top left to bottom right in Two
Dimensional Array including Diagonal Paths
Objective: Count all the paths from left top corner to right
bottom corner in two dimensional array.
Input: Two Dimensional array
Output: No of paths.
Approach :
1. Recursive
Recursive solution to this problem is similar to Print All
Paths from Top left to bottom right in Two Dimensional Array
But the Time complexity will be exponential because there will
be many sub problems which will be solved again and again to
get the final solution. read this : “Dynamic programming vs
Recursion
2. Dynamic Programming (Better Solution)
Create two dimensional resultCount array to store the number
of paths from top left corner.
Base Case: To reach to any cell in either first row or column
from first cell(top left at 0,0) will be 1.
You can reach to any cell from 3 different ways, from left,
from top, from diagonal. So total no of paths to reach to that
cell will be sum of all the paths to reach to left, top and
diagonal cell. see picture
17
Example:
Print All Paths from Top left to bottom right in Two Dimensional Array
Objective: Print all the paths from left top corner to right
bottom corner in two dimensional array.
Input: Two Dimensional array
Output: Print all the paths.
Note: At the End of the article you will know what needs to be
included if you want to print the diagonal paths as well.
Example:
18
Print All Elements of Two Dimensional Array in Spiral
Objective: This question was asked in Amazon interview for the
Software development Engineer position, Write an algorithm to
print all the elements of two dimensional array in spiral.
Example :
19
Print 2D array in Spiral
Input: Two dimensional array
Output: All array elements printed in spiral.
Find an Element in 2 dimensional sorted array
Objective : Write an algorithm to find an Element in 2
dimensional array where rows and columns are sorted
respectively.
Input: A two dimensional sorted array, arrA[][].
20
Output : True or false based on whether element exists and its
location
Expert
1. Find no of reverse pairs in an array which is sorted in two
parts in O(N)
Objective: Given an array of integers A[] which is sorted in
two parts (both parts are individually sorted), find no of
reverse pairs means no of (i, j) pairs where i belongs to the
part one and j belongs to part 2 and A[i]>A[j].
Example:
A[] = {4, 6, 8, 9, 1, 5, 10, 11} Output: 7
Explanation: Part one: {4, 6, 8, 9} Part two: {1, 5, 10, 11}
Reversed pairs: (4, 1) (6, 1) (6, 5) (8, 1) (8, 5) (9, 1) (9,
5) = 7
2. Count and print all Subarrays with product less than K in O(n)
21
Objective: Given an array of positive integers and integer
‘K’. Write an algorithm to count all the possible sub arrays
where product of all the elements in the sub array is less
than k.
Example:
Int [] nums = {10, 4, 2, 6}; K = 100 Output: 9 Sub arrays:
[10], [10 4], [10, 4, 2], [4], [4, 2], [4, 2, 6], [2], [2, 6],
[6]
3. Sliding Window Algorithm (Track the maximum of each subarray of
size k)
Objective: Given an array and integer k, write an algorithm to
find the maximum element in each subarray of size k.
Example:
int [] nums = { 1, 2, 3, 2, 4, 1, 5, 6,1}; Output: 3, 3, 4, 4,
5, 6, 6 Subarrays –
[1, 2, 3], max = 3 [2, 3, 2], max = 3 [3, 2, 4], max = 4 [2,
4, 1], max = 4 [4, 1, 5], max = 5 [1, 5, 6], max = 6 [5, 6,
1], max = 6
4. Print all sub sequences of a given array
Objective: Given an array write an algorithm to print all the
possible sub subsequences.
Example:
int [] a = {1, 2, 3}; Output: Possible sub sequences –
{Empty}, {1}, {2}, {3}, {1, 2} ,{1,3}, {2, 3}, {1, 2, 3}
5. Sum of all sub arrays in O(n) Time
Objective: Given an array write an algorithm to find the sum
of all the possible sub arrays.
Example:
22
int [] a = {1, 2, 3}; Output: Possible subarrays – {1}, {2},
{3}, {1, 2} , {2, 3}, {1, 2, 3} So sum = 1+ 2+ 3 + 3 + 5 + 6
= 20
6. Find two non-repeating numbers in an array in O(n) time and O(1)
space
Objective: Given an array of integers which has all the
repeating numbers (twice) but two numbers which are non-
repeating. Write an algorithm to find out those two numbers.
Example
int [] arrA = {4,5,4,5,3,2,9,3,9,8}; Output: 2 and 8
7. Maximum Subarray OR Largest Sum Contiguous Subarray Problem –
Divide and Conquer
Objective: The maximum subarray problem is the task of find-
ing the contiguous subarray within a one-dimensional array of
numbers which has the largest sum.
Example:
int [] A = {−2, 1, −3, 4, −1, 2, 1, −5, 4}; Output: contiguous
subarray with the largest sum is 4, −1, 2, 1, with sum 6.
8. Merge K Sorted Arrays
Objective: Given k sorted array, write an algorithm to merge
Them into One sorted array.
Example :
int[][] A = new int[5][];
A[0] = new int[] { 1, 5, 8, 9 };
A[1] = new int[] { 2, 3, 7, 10 };
A[2] = new int[] { 4, 6, 11, 15 };
A[3] = new int[] { 9, 14, 16, 19 };
A[4] = new int[] { 2, 4, 6, 9 };
Output:
23
[1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 9, 9, 9, 10, 11, 14, 15, 16,
19]
9. Print All Combinations of subset of size K from Given Array
Objective: Given an array of integers of size N, print all the
subsets of size k. (k<=N)
Example:
Generate all subsets of a fixed size k of a given set
[1,2,3…n]. e.g, if n=5 and k=3, the output will look like
1 2 3 1 2 4 1 2 5
1 3 4 1 3 5 1 4 5
2 3 4 2 3 5 2 4 5
3 4 5
10. Rearrange Positive and Negative Elements at Alternate
Positions in an Array In O(1) Extra Space
Objective: Given an array arrA[] which has negative and
positive elements, rearrange the array in such a manner that
positive and negative elements occupy the alternate positions
and if there are extra positive or negative elements are left
then append it to the end.
Examples:
int[] arrA = { 1, 2, -3, -4, -5, 6, -7, -8, 9, 10, -11, -12, -
13, 14 }; Output: -13 9 -3 10 -5 6 -7 2 -12 1 -11 14 -4 -8
11. Find All Elements in an Array which appears more than N/K
times, N is Array Size and k is a Number.
Objective: Given an array of size of N and number k. Find all
elements in an Array which appears more than N/K times.
Input: Array [] and number k.
Example:
24
int[] arrA = { 2, 2, 4, 4, 3, 5, 3, 4, 4, 6, 4, 3, 3, 8 }; K =
4 N/k = 14/4 = 3 Output will be [3,4] they appear 5, 4 times
respectively.
12. Rearrange Positive and Negative Numbers of Array On Each
Side in O(nlogn)
Objective: Rearrange Positive and Negative Numbers of an Array
so that one side you have positive numbers and other side with
negative Integers without changing their respective order.
Example : Input : 1 -2 3 -4 5 -6 7 -8 9 -10
ReArranged Output : -2 -4 -6 -8 -10 1 3 5 7 9
String
Easy
1. Find The Longest Sequence Of Prefix Shared By All The Words In A String
Objective: Write an algorithm to find The Longest Sequence of Prefix Shared by All the
Words in a String. This interesting problem was asked in the Google interview for software
engineer. This problem is bit tricky, it looks difficult but actually it is simple problem.
Input: A String
Output: The longest sequence of prefix common in all the words in a string
Example:
“Bedroom BedClock BedTable BedWall” => “Bed”
2. Valid Brackets – Part 2 | Stack Method
Objective: Given a string containing just the characters ( , ) determine if the input string is
valid.
Example:
()()(()(()))() valid: true
)()()( valid: false
()()) valid: false
3. Given two strings validate the output string
Objective: Given two input strings and one output strings, validate if output string contains
all the characters from both the input strings.
25
Example:
Input1 = "boy", Input2 = "girl", output = "gboilry"
Result = True
Input1 = "tutorial", Input2 = "horizon", output =
"tuhotoririzoialn" Result = True
Input1 = "boy", Input2 = "girl", output = "bogiry" Result =
False
4. Find Largest and Smallest word in a given String
Objective: Given a String, write a program to find largest and smallest word in it.
Example:
Input String: test Smallest Word: test Largest Word: test
------------------
Input String: This problem is solved at Algorithms tutorial
horizon
Smallest Word: is Largest Word: Algorithms
5. Find Largest and Smallest word in a given String
Objective: Given a String, write a program to find largest and smallest word in it.
Example:
Input String: test Smallest Word: test Largest Word: test
------------------
Input String: This problem is solved at Algorithms tutorial
horizon
Smallest Word: is Largest Word: Algorithms
6. Reverse the given String using Stack
Objective: Given a String, write a java program to reverse the string using Stack
Example:
26
Input: “tutorial horizon” Output: “noziroh lairotut”
7. Check if two Strings are equal without using built-in function – Java
Objective– Given two strings, find out if they are equal or not without using any built-in
function (without using equals() function in java).
Example:
String x='tutorial' and String y='tutorial' are equal – true
String x='tutorial' and String y='tutorial ' are equal – false
String x='tutorial' and String y=' ' are equal – false
8. Remove Vowels from a given String
Objective: Given a String, remove all the vowels from the string.
What Are Vowels?
The letters A, E, I, O, and U are called vowels. The other letters in the alphabet are called
consonants.
Example:
Input String: algorithms @ tutorial horizon
Updated String: lgrthms @ ttrl hrzn
9. Reverse a String using Recursion
Objective: Given a String, write a recursive program to reverse it.
Example:
Original String: tutorial horizon
Reversed String: noziroh lairotut
10. Print maximum occurring character in a String
Objective– Given a string, write an algorithm to find the character in string which occurs
maximum number of times. If more than one character has maximum and same count then
print all of them
Example:
27
Input- tutorial horizon
Character: o has occurred max times: 3
----------------------
Input- abcabcdefabcab
Character: a has occurred max times: 4
Character: b has occurred max times: 4
11. Sort Names by their Last Names.
Objective: Given a list of names ( first name and last name), sort the list by their last names.
Example:
List [] = {"Daenerys Targaryen", "Jon Snow", " Tyrion
Lannister", " Joffrey Baratheon"} Output: [Joffrey Baratheon,
Tyrion Lannister, Jon Show, Daenerys Targaryen]
12. Check if one string is Rotation of another string
Objective: Write an algorithm to check if one string is Rotation of another string. This
question has been asked in the Amazon interview.
Example:
Input Strings : 'sumitjain' and 'tjainsumi' Output : true
Input String : 'Jaain' and 'ainJ' Output: false
13. String Compression using count of repeated characters – Run Length Encoding
Objective: Write an algorithm to compress the given string by using the count of repeated
characters and if new compressed string length is not smaller than the original string then
return the original string.
Example:
Input String : ssssuuuummmmmmiiiittttttttttttt
Compressed String : s4u4m6i4t13 Input String : Jaain
Compressed String : Jaain (Since compressed string is length
is greater than original string)
28
14. Find Whether Two Strings are Permutation of each other
Objective: Given Two Strings, check whether one string is permutation of other
Input: Two Strings
Output: True or false based on whether strings are permutation of other or not.
Example:
"sumit" and "tiums" are permutations of each other.
"abcd" and bdea" are not permutations of each other.
15. Check If String has All Unique Characters
Objective: Write an algorithm to find out whether in a given string contains all the unique
characters. This question has been asked in the Amazon and Microsoft interviews.
Input: A String
Output: True or false based upon whether string contains all the unique characters or not.
Intermediate
1. Valid Multiple Parentheses
Objective: Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine
if the input string is valid.
Example:
()()([]({}))[] valid: true
()({]) valid: false
[]{}() valid: true
[(}{)] valid: false
2. Generate all the strings of length n from 0 to k-1.
Objective: Given two numbers, n and k (k>=n), write an algorithm to generate all the strings
of length n drawn from 0 – k-1.
Example:
k = 2, n = 2
Output: 0 0 0 1 1 0 1 1
k = 3, n = 2
29
Output:
0 0 1 0 2 0 0 1 1 1 2 1
0 2 1 2 2 2
3. Find number of Distinct Permutations of a String
Objective – Given a string, find the number of distinct permutations or anagrams of that
string.
Example:
String x = "abc" Output: 6 (abc, acb, bac, bca, cab, cba)
String x = "aab" Output: 3 (aab, aba, baa)
4. Replace all vowels with next consonant in a given string
Objective: Given a string, write an algorithm to replace all the vowels with next consonant,
and if last alphabet is vowel, remove it.
Example:
String input: “abcdefg” Output: “bbcdffg”
String input: “aaaabccceee” Output: “bbbbbccc”
String input: “aaa” Output: “”
5. Minimum Copy Paste Operations
Objective: You have given a character ‘A’ which is already printed. You are allowed to
perform only 2 operations –
1. Copy All – This operation will copy all the printed characters.
2. Paste – This operation will paste all the characters which are already copied.
Given a number N, write an algorithm to print character ‘A’ exactly N times with minimum
no of operations (either copy all or paste)
Example:
Character – A N = 6 Option 1:
30
Copy All – this will copy ‘A’
Paste – output “AA” Paste – output “AAA”
Paste – output “AAAA” Paste – output “AAAAA” Paste – output
“AAAAAA”
Total operations – 6
Option 2:
Copy All – this will copy ‘A’ Paste – output “AA” Paste –
output “AAA” Copy All Paste – output “AAAAAA”
Total operations – 5
Since with option 2, the task is done in 5 operations. Minimum
operations – 5
6. Print all sub sequences of a given String
Objective: Given a String write an algorithm to print all the possible sub subsequences.
Example:
String input = “abc”; Output: Possible sub sequences –
Empty}, {a}, {b}, {c}, {ab} ,{a,c}, {b, c}, {a, b, c}
7. Print all substrings of a given string
Objective: Given a string write an algorithm to print all the possible sub strings.
Example:
String input = “abcd”;
Output: Possible sub strings –
a a b a b c a b c d
b b c b c d
c c d
d
Approach:
31
8. Remove Duplicates from a string
Objective: Given a string, write an algorithm to remove the duplicate characters in that
string.
Example:
Input: tutorialhorizon
Output: tuorialhzn
9. All N Length Strings from Given String of Length K
Objective: Print All N Length Strings from Given String of Length K where characters can
appear multiple time.
Example:
String k = "ALGO" N=2
Result: AA LA GA OA AL LL GL OL AG LG GG OG AO LO GO OO
10. Find All the Well Ordered Permutations of a Given String.
Objective: Write an algorithm to Print All the Well Ordered Permutations of a Given String.
What is Well Ordered String: When all the alphabets in a string occur in the increasing
order irrespective of Lower Case or Upper case.
http://www.careercup.com/question?id=6206517812396032
Example :
"Sumit" - Not Well Ordered . 'u' occurred after 'S'.
"Now" - Well Ordered. N<o<W.
Input: Interview
Output: [e, e, I, i, n, r, t, v, w]
[e, e, i, I, n, r, t, v, w]
[e, e, i, I, n, r, t, v, w]
[e, e, I, i, n, r, t, v, w]
11. Replace all spaces in a String with ‘%20’
Objective: Write an algorithm to replace all spaces in a given string with ‘%20’. You can
consider that string has enough space at the end of the string to hold the extra characters.
Input: A String and true length of a string
Output: Updated string in which each space is replaced by the ‘%20’
32
Example: Input String : I am Sumit Jain
Output String : I%20am%20Sumit%20Jain
12. Valid or Well Formed Parentheses | Part – 1
Objective: You have been asked to Write an algorithm to find Whether Given the Sequence
of parentheses are well formed. This question was asked in the Amazon Interview.
Input: A String contains a sequence of parentheses
Output: true or false on whether parentheses are well formed or not
Expert
1. Text Justification Problem (OR Word Wrap Problem)
Objective: Given a list of words and length L. Format the words so that each line will have
only L characters and fully justified (left and right justified).
Restrictions-
You need to fit as many as words in every line.
You are not allowed to split a word and put them in next line.
Pad extra spaces ‘ ‘ if needed so that each line has L characters.
Extra spaces between words should be distributed as evenly as possible. If even
distribution is not possible then extra spaces will be assigned on the left most
space (between two words).
Assumption – Each word has length less than Length L.
Example:
String [] words = {"This", "is", "a", "text",
"justification","problem","in","tutorial","horizon"};
int length = 20;
Output: This is a text justification problem in tutorial
horizon
2. Print All N Length Strings from Given Number K
Objective: Given Number K, Print all the strings of N length.
Example:
33
N = 2, K = 3
[1, 1] [2, 1] [3, 1] [1, 2] [2, 2] [3, 2] [1, 3] [2, 3] [3, 3]
3. The Word Break Problem
Objective : Given an string and a dictionary of words, find out if the input string can be
broken into a space-separated sequence of one or more dictionary words.
Example:
dictionary = ["I" , "have", "Jain", "Sumit", "am", "this",
"dog"]
String = "IamSumit" Output: "I am Sumit"
String ="thisisadog" Output : String can't be broken
4. Print All Possible Valid Combinations Of Parenthesis of Given ‘N’
Objective: – Given “n”, generate all valid parenthesis strings of length “2n”.
Example:
Given n=2
Output:
(())
()()
5. Print All The Permutations Of a String
Objective: Given a String, print all the permutations of it.
Input: A String
Output: Print all the permutations of a string
Example:
Input : abc Output: abc acb bac bca cba cab
34