Important Practice questions on click of this link
Programming Interview questions
One more
1. Find 2nd largest number in an given array.
Constraint : 1. can only access each number by 1 times only.
2. Don't use any collection/Object. use only primitive type like int.
3. Complexity : O(n)Solution:
Below is the complete algorithm for doing this:
1) Initialize two variables first and second to INT_MIN as
first = second = INT_MIN
2) Start traversing the array,
a) If the current element in array say arr[i] is greater
than first. Then update first and second as,
second = first
first = arr[i]
b) If the current element is in between first and second,
then update second to store the value of current variable as
second = arr[i]
3) Return the value stored in second.
class
GFG {
public
static
void
print2largest(
int
arr[],
int
arr_size)
{
int
i, first, second;
if
(arr_size <
2
) {
System.out.print(
" Invalid Input "
);
return
;
}
first = second = Integer.MIN_VALUE;
for
(i =
0
; i < arr_size; i++) {
if
(arr[i] > first) {
second = first;
first = arr[i];
}
else
if
(arr[i] > second && arr[i] != first)
second = arr[i];
}
if
(second == Integer.MIN_VALUE)
System.out.print(
"There is no second largest"
+
" element\n"
);
else
System.out.print(
"The second largest element"
+
" is "
+ second);
}
public
static
void
main(String[] args)
{
int
arr[] = {
12
,
35
,
1
,
10
,
34
,
1
};
int
n = arr.length;
print2largest(arr, n);
}
}
2.) Longest substring with unique char (Without repeating) i/p : abcabdefgb ; o/p : defg
Answer: We start traversing the string from left to right and maintain track of:
- the current substring with non-repeating characters with the help of a start and end index
- the longest non-repeating substring output
- a lookup table of already visited characters
String getUniqueCharacterSubstring(String input) {
Map<Character, Integer> visited = new HashMap<>();
String output = "";
for (int start = 0, end = 0; end < input.length(); end++) {
char currChar = input.charAt(end);
if (visited.containsKey(currChar)) {
start = Math.max(visited.get(currChar)+1, start);
}
if (output.length() < end - start + 1) {
output = input.substring(start, end + 1);
}
visited.put(currChar, end);
}
return output;
}
For every new character, we look for it in the already visited characters. If the character has already been visited and is part of the current substring with non-repeating characters, we update the start index. Otherwise, we'll continue traversing the string.
Since we are traversing the string only once, the time complexity will be linear, or O(n).
This approach is also known as the sliding window pattern.
3.)Next immediate bigger number, using combination of digit. ex : i/p :1234 ;o/p :1243
Solution:
Following are few observations about the next greater number.
1) If all digits sorted in descending order, then output is always “Not Possible”. For example, 4321.
2) If all digits are sorted in ascending order, then we need to swap last two digits. For example, 1234.
3) For other cases, we need to process the number from rightmost side (why? because we need to find the smallest of all greater numbers)
You can now try developing an algorithm yourself.
Following is the algorithm for finding the next greater number.
I) Traverse the given number from rightmost digit, keep traversing till you find a digit which is smaller than the previously traversed digit. For example, if the input number is “534976”, we stop at 4 because 4 is smaller than next digit 9. If we do not find such a digit, then output is “Not Possible”.
II) Now search the right side of above found digit ‘d’ for the smallest digit greater than ‘d’. For “534976″, the right side of 4 contains “976”. The smallest digit greater than 4 is 6.
III) Swap the above found two digits, we get 536974 in above example.
IV) Now sort all digits from position next to ‘d’ to the end of number. The number that we get after sorting is the output. For above example, we sort digits in bold 536974. We get “536479” which is the next greater number for input 534976.
import
java.util.Arrays;
public
class
nextGreater
{
static
void
swap(
char
ar[],
int
i,
int
j)
{
char
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
static
void
findNext(
char
ar[],
int
n)
{
int
i;
for
(i = n -
1
; i >
0
; i--)
{
if
(ar[i] > ar[i -
1
]) {
break
;
}
}
if
(i ==
0
)
{
System.out.println(
"Not possible"
);
}
else
{
int
x = ar[i -
1
], min = i;
for
(
int
j = i +
1
; j < n; j++)
{
if
(ar[j] > x && ar[j] < ar[min])
{
min = j;
}
}
swap(ar, i -
1
, min);
Arrays.sort(ar, i, n);
System.out.print(
"Next number with same"
+
" set of digits is "
);
for
(i =
0
; i < n; i++)
System.out.print(ar[i]);
}
}
public
static
void
main(String[] args)
{
char
digits[] = {
'5'
,
'3'
,
'4'
,
'9'
,
'7'
,
'6'
};
int
n = digits.length;
findNext(digits, n);
}
}
5.) Given a String "Kunwar jee Pathak". Print output as "Kunwr j Pthk" . All duplicates to be removed.
Solution
1) By using indexOf() method
Thisway of removing duplicate characters from a string is by using the indexOf() method. In this method, we will work on the index position of the character. In order to remove the duplicate character from the string, we will use the following steps:
- In the main() method, we will create a string from which we have to remove duplicate characters.
- We will call the removeDuplicates() method and passed the string from which we need to remove duplicate characters.
- In the removeDuplicates() method, we will create a new empty string and calculate the original string's length.
- We will traverse the string using the loop and check for repeating characters using the indexOf() method.
- The indexOf() method returns -1 when the element is not present. So, when the string doesn't contain that character, we will add it to the empty string.
RemoveDuplicatesExample4.java
-
- import java.util.*;
-
- class RemoveDuplicatesExample4 {
-
-
- public static void removeDuplicates(String str)
- {
-
- String newstr = new String();
-
-
- int length = str.length();
-
-
- for (int i = 0; i < length; i++)
- {
-
- char charAtPosition = str.charAt(i);
-
- if (newstr.indexOf(charAtPosition) < 0)
- {
- newstr += charAtPosition;
- }
- }
-
- System.out.println(newstr);
- }
-
-
- public static void main(String[] args)
- {
-
- String str = "JavaTpoint is the best learning website";
-
- removeDuplicates(str);
- }
- }
By using for loop
It is the simplest way of removing duplicates characters from a string. We should have to use the following steps for removing duplicates.
- In the first step, we have to convert the string into a character array.
- Calculate the size of the array.
- Call removeDuplicates() method by passing the character array and the length.
- Traverse all the characters present in the character array.
- Check whether the str[i] is present before or not. If it is not present before, add it to the result.
Let's implement the above theory's code to understand how this method works to remove duplicates from a string.
RemoveDuplicatesExample1.java
-
- import java.util.*;
-
-
- class RemoveDuplicatesExample1
- {
-
- static void removeDuplicate(char str[], int length)
- {
-
- int index = 0;
-
-
- for (int i = 0; i < length; i++)
- {
-
-
- int j;
- for (j = 0; j < i; j++)
- {
- if (str[i] == str[j])
- {
- break;
- }
- }
-
-
- if (j == i)
- {
- str[index++] = str[i];
- }
- }
- System.out.println(String.valueOf(Arrays.copyOf(str, index)));
- }
-
-
- public static void main(String[] args)
- {
- String info = "javaTpoint is the best learning website";
-
- char str[] = info.toCharArray();
-
- int len = str.length;
-
- removeDuplicate(str, len);
- }
- }
6.) Find Missing Number
input[1,2,7,6,4,3]
output[5]
Use Sum formula
-> Get the sum of number
total= n*(n+1)/2;
-> Subtract all the numbers from the sum and you will find missing number
int main()
{
int a[]= {1,2,4,5,6}
int miss= getMissingNo(a,5)
}
int getMissingNo(int a[], int n)
{
int i, total;
total = (n+1)*(n+2)/2;
for(int i=0; i<n; i++){
total = total - a[i];
return total;
}
7.) Insert Operation
//In an unsorted array, the insert operation is faster as compared to sorted array because we don't have //to care about the position at which the element to be placed.
int main()
{
int arr[20] = {12,16,20,40,50,70};
int capacity = sizeof(arr)/sizeof(arr[0]);
int n=6;
int i, key=26;
n = insertSorted(arr, n .key, capacity);
}
// Inserts a key in arr[] of given capacity, n is current size of arr[]. This function returns n+1 if //insertion is successful else n.
int insertSorted( int arr[], int n, int key, int capacity)
{
if( n>= capacity)
return n;
int i;
for ( i=n-1; (arr[i] > key && i>0); i--)
{
arr[i+1] = arr[i];
}
arr[i+1]=key;
return(n+1);
//after for loop
}
8.) Search, Insert and Delete in a sorted array
1.) Search using binary:
int main()
{
int arr[]={5,6,7,8,9,10};
int n, key;
n=sizeof(arr)/sizeof(arr[0]);
key=10;
binarySearch(arr, 0, n, key);
}
int binarySearch( int arr[], int low, int high, int key)
{
if( high < low)
return-1;
int mid = (low+high)/2;
if ( key == arr[mid])
return mid;
if (key > arr[mid])
return binarySearch( arr, (mid+1), high, key);
return binarySearch(arr, low, (mid-1), key);
}
9.) Delete Operation
//The element to be deleted is searched using binary and then delete operation is performed by //shifting the elements
int main()
{
int i;
int arr[] = {10,20,30,40,50};
int n = sizeof(arr) / sizeof(arr[0]);
int key =30;
n = deleteElement(arr, n , key);
}
int deleteElement ( int arr[], int n, int key)
{
//find position of element to be deleted
int pos = binarySearch(arr, 0, n-1, key);
if (pos ==-1)
{ //element not found}
//deleting
int i;
for( i=pos; i<n; i++){
arr[i] = arr[i+1];
}
return n-1;
}