DSA Interview Coding Questions
1] Arrays
1] Find first and second best score Example
Given an array, write a function to get first, second best scores from the array and return it in new array.
Array may contain duplicates.
Example
- myArray = {84,85,86,87,85,90,85,83,23,45,84,1,2,0}
- firstSecond(myArray) // {90, 87}
- Solution:
- import java.util.Arrays;
- import java.util.Collections;
- public class Exercise {
- public static int[] findTopTwoScores(int[] array) {
- int firstHighest = Integer.MIN_VALUE;
- int secondHighest = Integer.MIN_VALUE;
- for (int score : array) {
- if (score > firstHighest) {
- secondHighest = firstHighest;
- firstHighest = score;
- } else if (score > secondHighest && score < firstHighest) {
- secondHighest = score;
- }
- }
- return new int[]{firstHighest, secondHighest};
- }
- }
2] Missing Number from unique element Array
Write Java function called
findMissingNumberInArray
that takes an integer array containing n-1 unique elements from a range of 1 to n, with one missing number, and returns the missing number.Example
- myArray = {1,2,3,4,6}
- findMissingNumberInArray(myArray, 6) // 5
Hint:
Use the formula
(n * (n + 1)) / 2
which calculates the sum of the first n natural numbers.
- public class Exercise {
- public static int findMissingNumberInArray(int[] array) {
- int n = array.length + 1;
- int expectedSum = (n * (n + 1)) / 2;
- int actualSum = 0;
- for (int number : array) {
- actualSum += number;
- }
- return expectedSum - actualSum;
- }
- }
2] Find Duplicates Number
Write a function which takes integer array as a parameter and returns a new integer array with unique elements. (remove duplicates)
Example
- removeDuplicates({1, 1, 2, 2, 3, 4, 5})
- Output : [1, 2, 3, 4, 5]
- public class Exercise {
- public static int[] removeDuplicates(int[] array) {
- int n = array.length;
- int[] uniqueArray = new int[n];
- int index = 0;
- for (int i = 0; i < n; i++) {
- boolean isDuplicate = false;
- for (int j = i + 1; j < n; j++) {
- if (array[i] == array[j]) {
- isDuplicate = true;
- break;
- }
- }
- if (!isDuplicate) {
- uniqueArray[index++] = array[i];
- }
- }
- return Arrays.copyOf(uniqueArray, index);
- }
- }
Comments
Post a Comment