Find Pairs with Given Sum in a Sorted Array – Java Code

Java code to find pairs with given sum in a sorted array. Given an array A of size N. Write a java code to find all pairs in the array that sum to a number equal to K. If no such pair exists then output will be 1.  Array elements are distinct and in a sorted order.

For example –

Input :

arr[] = {1, 2, 3, 4, 5, 6, 7};
sum = 9

Output:

Pairs with given sum 9 is

Pair (2 , 7 )
Pair (3 , 6 )
Pair (4 , 5 )

Segregate 0s and 1s in an Array – Java Code

Segregate 0s and 1s in an Array. Given an array of 0s and 1s in random order. Write a java program to segregate 0’s on left side and 1’s on right side of the array.

Subscribe Our Tutorials

Get Latest Updates on Facebook

For example –

Input array = [0, 1, 0, 1, 0, 0, 1]
Output array = [0, 0, 0, 0, 1, 1, 1]

Find First and Last Position of a Number in a Sorted Array – Java Code

Given a sorted array which contains duplicate elements, Write a java code to find first and last position of a number in a sorted array. Given a number x, write a code to find it’s first and last index in an array.

For example –

Suppose the input array is arr[] : {1, 4, 7, 8, 8, 11, 11, 11, 11, 12, 13, 13} and the number to be searched is 11. Then the first index of 11 is 5 and last index is 8.

Find Intersection of Two Arrays – Java Code

Given two sorted arrays, Write a java code to find intersection of two arrays.

For example, if the input arrays are:

arr1[] = {2, 3, 6, 7, 9, 11}
arr2[] = {4, 6, 8, 9, 12}

Then your program should print intersection as {6, 9}. Before writing actual code, let’s first discuss different approaches to solve this problem.

Move All Zeroes to End of Array – Java Code

Given an array of random integers, we have to write a function to move all zeroes to end of array. The order of all other elements of an array should be same.

For example –

Input : {1, 2, 0, 4, 0, 5, 3, 8}

Output: {1, 2, 4, 5, 3, 8, 0, 0}

In this tutorial, I am going to discuss how we can move all zeroes to end of array using java program. So, first i am going to discuss the algorithm and after that we’ll see how we can implement this algorithm using java code. At the end of this post you’ll find a video tutorial.

This question is mostly asked in a technical interviews.