0% found this document useful (0 votes)
55 views18 pages

Array Codes and Interview Questions

Q&A

Uploaded by

Sarupya Datta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views18 pages

Array Codes and Interview Questions

Q&A

Uploaded by

Sarupya Datta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

ARRAY CODES AND INTERVIEW QUESTIONS

public class SingleDimensionArray {


int arr[] = null;

public SingleDimensionArray(int sizeOfArray) {


arr = new int[sizeOfArray];
for (int i=0; i<arr.length; i++) {
arr[i] = Integer.MIN_VALUE;
}
}

public void insert(int location, int valueToBeInserted) {


try {
if (arr[location] == Integer.MIN_VALUE) {
arr[location] = valueToBeInserted;
System.out.println("Successfully inserted");
} else {
System.out.println("This cell is already
occupied");
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid index to access
array!");
}
}
// Array Traversal

public void traverseArray() {


try {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
} catch (Exception e) {
System.out.println("Array no longer exists!");
}

//Search for an element in the given Array


public void searchInArray(int valueToSearch) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == valueToSearch) {
System.out.println("Value is found at the index of "
+ i);
return;
}
}
System.out.println(valueToSearch + " is not found");
}

// Delete value from Array


public void deleteValue(int valueToDeleteIndex) {
try {
arr[valueToDeleteIndex] = Integer.MIN_VALUE;
System.out.println("The value has been deleted
successfully");

} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("The value that is provided is not
in the range of array");

}
}

public class TwoDimensionalArray {


int arr[][] = null;

// Constructor
public TwoDimensionalArray(int numberOfRows, int
numberOfColumns) {
this.arr = new
int[numberOfRows][numberOfColumns];
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[0].length; col++)
{
arr[row][col] = Integer.MIN_VALUE;
}
}
}

// Inserting value in the Array


public void insertValueInTheArray(int row, int col, int
value) {
try {
if (arr[row][col] == Integer.MIN_VALUE) {
arr[row][col] = value;
System.out.println("The value is successfully
inserted");
} else {
System.out.println("This cell is already occupied");
}

} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid index for 2D array");
}
}

// Accessing cell value from given array


public void accessCell(int row, int col) {
System.out.println("\nAccessing Row#" + row + ",
Col#" + col);
try {
System.out.println("Cell value is: " + arr[row][col]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid index for 2D array");
}
}

// Traverse 2D array

public void traverse2DArray() {


for (int row=0; row < arr.length; row++) {
for (int col=0; col < arr[0].length; col++) {
System.out.print(arr[row][col] + " ");
}
System.out.println();
}
}

// Searching a single value from the Array


public void searchingValue(int value) {
for (int row=0; row<arr.length; row++){
for (int col=0; col<arr[0].length; col++) {
if (arr[row][col] == value) {
System.out.println("Value is found at row: "+ row
+ " Col: " + col);
return;
}
}
}
System.out.println("Value is not found");
}

// Deleting a value from Array


public void deleteValuefromArray(int row, int col) {
try {
System.out.println("Successfully deleted: " +
arr[row][col]);
arr[row][col] = Integer.MIN_VALUE;

} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("This index is not valid for
array");
}
}
}

Array Project: --

import java.util.*;
class Main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many days' temperatures? ");
int numDays = console.nextInt();
int[] temps = new int[numDays];
// record temperatures and find average
int sum = 0;
for (int i=0; i<numDays; i++) {
System.out.print("Day " + (i+1) + "'s high temp: ");
temps[i] = console.nextInt();
sum += temps[i];
}

double average = sum / numDays;


// count days above average
int above = 0;
for (int i=0; i<temps.length; i++) {
if (temps[i]>average) {
above++;
}
}
System.out.println();
System.out.println("Average Temp = " + average);
System.out.println(above + " days above average");

}
}

Problem with solutions


Write a function called middle that takes an array and
returns a new array that contains all but the first and
last elements.
myArray = [1, 2, 3, 4]
middle(myArray) # [2,3].

public class Exercise {


public static int[] middle(int[] array) {

if (array.length <= 2) {
return new int[0]; // Return an empty array if the input array
has 2 or fewer elements
}

// Create a new array with a size of the input array length minus
2

int[] middleArray = new int[array.length - 2];

// Copy the elements from the input array, excluding the first and
last elements

int index = 1;
while (index < array.length - 1) {

middleArray[index - 1] = array[index];

index++;
}

return middleArray;

}
}
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}

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};

}
}
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);

}
Two Sum
Given an array of integers nums and an integer target, return
indices of the two numbers such that they add up to target. You
may assume that each input would have exactly one solution,
and you may not use the same element twice.

Examples
Input: nums = [2,7,11,15], target = 9

Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1]

public class Exercise {


public int[] twoSum(int[] nums, int target) {

for (int i = 0; i < nums.length; i++) {


for (int j = i + 1; j < nums.length; j++) {

if (nums[i] + nums[j] == target) {


return new int[] { i, j };

}
}
throw new IllegalArgumentException("No two sum solution
found");

}
}

Finding a Number in an Array

Write a program to to check if an array contains a number in Java.


1. int[] intArray = {1,2,3,4,5,6};

2. searchInArray(intArray, 6); // 5

class Main {

public static void main(String[] args) {


Main mn = new Main();

int[] intArray = {1,2,3,4,5,6};


mn.linearSearch(intArray, 7);

// Search Method
public void linearSearch(int[] intArray, int value) {

for(int i=0; i<intArray.length; i++) {


if (intArray[i] == value) {

System.out.println("Value is found at the index of " + i);


return;

}
}

System.out.println(value + " is not found");


}

Given 2D array calculate the sum of diagonal elements.


Example

1. myArray2D= {{1,2,3},{4,5,6},{7,8,9}};
2.

3. sumDiagonalElements(myArray2D) # 15

public class Exercise {

public static int sumDiagonalElements(int[][] array) {


int sum = 0;

int numRows = array.length;

for (int i = 0; i < numRows; i++) {


sum += array[i][i];

return sum;
}

Best Score
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}

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;
}

}
Missing Number
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
1. myArray = {1,2,3,4,6}

2. 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;

}
}

Best Time to Buy and Sell Stock


You are given an array prices where prices[i] is the price of a
given stock on the ith day. You want to maximize your profit by
choosing a single day to buy one stock and choosing a different
day in the future to sell that stock. Return the maximum profit you
can achieve from this transaction. If you cannot achieve any
profit, return 0.
Example:

1. Input: prices = [7, 1, 5, 3, 6, 4]


2. Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price =
6), profit = 6-1 = 5.
public class Exercise {

public int maxProfit(int[] prices) {


int minPrice = Integer.MAX_VALUE;

int maxProfit = 0;

for (int price : prices) {

if (price < minPrice) {


minPrice = price;

} else if (price - minPrice > maxProfit) {


maxProfit = price - minPrice;

return maxProfit;
}

}
In this solution, we iterate through the prices array using a for-each loop.
We maintain two variables: minPrice to keep track of the lowest price
encountered so far, and maxProfit to store the maximum profit achieved.
As we iterate through the array, we check if the current price is less than
the current minPrice. If so, we update the minPrice with the current
price. If the current price is not less than minPrice, we check if the profit
made by selling at the current price (i.e., price - minPrice) is greater
than the current maxProfit. If so, we update the maxProfit with the
new profit. Finally, we return maxProfit as the maximum profit that can
be achieved from the given stock prices.

Permutation
Your are given two integer arrays. Write a program to check if
they are permutation of each other.
Example

1. int[] array1 = {1,2,3,4,5};


2. int[] array2 = {5,1,2,3,4};

3. permutation(array1, array2)
Output

true
class Main {
public static void main(String[] args) {

Main mn = new Main();


int[] array1 = {1,2,3,4,5};

int[] array2 = {5,4,3,2,1,0};


boolean result = mn.permutation(array1, array2);

System.out.println(result);

// Permutation

public boolean permutation(int[] array1, int[] array2){


if (array1.length != array2.length ) {

return false;
}

int sum1 = 0;
int sum2 = 0;

int mul1 = 1;

int mul2 = 1;

for (int i = 0; i<array1.length; i++) {


sum1 += array1[i];

sum2 += array2[i];
mul1 *= array1[i];

mul2 *= array2[i];
}

if (sum1 == sum2 && mul1 == mul2) {


return true;

}
return false;
}

Rotate Matrix
Given an image represented by an NxN matrix write a method to
rotate the image by 90 degrees.
You have to rotate the image in-place, which means you have to
modify the input 2D matrix directly.

DO NOT allocate another 2D matrix and do the rotation.

import java.util.Arrays;

class Main {
public static void main(String[] args) {

Main mn = new Main();

int[][] matrix = {{1,2,3}, {4,5,6}, {7,8,9}};


mn.rotateMatrix(matrix);

System.out.println(Arrays.deepToString(matrix));

public boolean rotateMatrix(int[][] matrix) {


if (matrix.length == 0 || matrix.length != matrix[0].length) return
false;

int n = matrix.length;
for (int layer = 0; layer < n/2; layer++) {

int first = layer;


int last = n - 1 - layer;

for (int i=first; i<last; i++) {

int offset = i - first;


int top = matrix[first][i];
matrix[first][i] = matrix[last-offset][first];
matrix[last-offset][first] = matrix[last][last-offset];

matrix[last][last-offset] = matrix[i][last];
matrix[i][last] = top;

}
return true;

You might also like