11 Java Beginner Level Implementation Interview Questions & Answers
Below is a list of our Java Beginner Level Implementation interview questions. Click on any interview question to view our answer advice and answer examples. You may view 5 answer examples before our paywall loads. Afterwards, you'll be asked to upgrade to view the rest of our answers.
1. Validate a square.
This interview question shows a developer's knowledge of Java functions.
You are given four points in 2-D space. Return true if they form a square, false otherwise. The points are integer coordinates and are given in any order.
Valid square- A quadrilateral with all sides equal and both diagonal equal. Also, each interior angle is equal to 90°.
/*Example*/
Input- [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Expected output- true
Input- [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]
Expected output- false
Solution:
For four points, we can find distances between them. There are a total of 6 distances possible. To be a valid square, 4 of them should be equal (the sides) and 2 should be equal (diagonals), and satisfies the following condition (Pythagoras theorem)-
diagonal2 = 2 * side2
Instead of storing actual sides or diagonal, we are storing their square to avoid precision loss due to imperfect squares.
import java.util.*;
class Solution {
public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4){
ArrayList<Double> distances = new ArrayList<Double>();
ArrayList<int[]> points = new ArrayList<int[]>();
points.add(p1);
points.add(p2);
points.add(p3);
points.add(p4);
for (int i = 0; i < 4; i++) {
int[] point1 = points.get(i);
for (int j = i + 1; j < 4; j++) {
int[] point2 = points.get(j);
distances.add(getDistanceSquared(point1, point2));
}
}
ArrayList<Double> d1 = new ArrayList<Double>();
ArrayList<Double> d2 = new ArrayList<Double>();
for (int i = 0; i < distances.size(); i++) {
Double firstDistance = distances.get(0);
Double ithDistance = distances.get(i);
if (Double.compare(firstDistance, ithDistance) == 0) {
d1.add(ithDistance);
} else {
d2.add(ithDistance);
}
}
//Remove value which doesn’t match with the first value.
d2.removeIf(n -> (Double.compare(n, d2.get(0)) != 0));
return areValidSides(d1, d2) || areValidSides(d2, d1);
}
private boolean areValidSides(ArrayList<Double> diagonals,
ArrayList<Double> sides) {
if (diagonals.size() != 2 || sides.size() != 4) {
return false;
}
return (sides.get(0) * 2 == diagonals.get(0));
}
private double getDistanceSquared(int[] p1, int[] p2) {
double diffXSquared = Math.pow(p1[0] - p2[0], 2);
double diffYSquared = Math.pow(p1[1] - p2[1], 2);
return diffXSquared + diffYSquared;
}
}
Time complexity- O(1) // only four points
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
2. Format a string by grouping characters found in the string into similar lengths.
This question tests that a developer is familiar with Java textual data.
You are given a string named string consisting of alphanumeric characters. It contains some dashes - at random places dividing the string into groups. These groups can be of different or the same length. Your task is to format the string such that the dashes divide the string into groups of equal length K. The first group may have a length of less than or equal to K but the rest of the groups must have length K.
/*Example*/
Given - “abc-def†and K = 2
Expected output - “ab-cd-efâ€
//All groups have the same length 2.
Given - “abc-def-abdj-k†and K = 3
Expected output - “ab-cde-fab-djkâ€
All groups have except the first group has the same length 3.
Solution:
Given string - string
Let, the normal length of groups (except for the first group) be K
Let, the length of the given string be L
Let, the count of alphanumeric characters be N
If K divides N, then there are exactly K / N such groups in the formatted string each of length K.
If K does not divide N, then there are floor(K / N) groups each of length K and one group with remaining characters. The first group will have fewer than K characters and the rest will have exactly K characters. It is guaranteed that its length will be at least 1 because K does not divide N.
Let’s understand the sample inputs.
Given string- “abc-defâ€
Given K = 2
N = 6
Since K divides N, there will be 6 / 2 = 3 groups in the formatted string.
---
Given string- “abc-def-abdjkâ€
Given K = 3
N = 11
Since K does not divide N, there will be floor(11 / 3) = 3 groups in the formatted string with length K = 3 viz. cde, fab, djk. The remaining two characters ab will form the first group with length <= K = 3.
It can be seen there will be a dash - after every K places in the given string (with dashes removed). Thus we can iterate on the given string in the backward direction and place a dash after every K alphanumeric character.
class Solution {
public String licenseKeyFormatting(String s, int k) {
StringBuilder characters = new StringBuilder();
// iterate backwards
for (int i = s.length() - 1; i >= 0; i--) {
char ch = s.charAt(i);
// if the current character is a dash skip it
if (ch == '-') continue;
// if the `characters` array contains a group
// of size `k` in its tail, push a dash
// marking the start of a new group
if (characters.length() % (k + 1) == k) {
characters = characters.append('-');
}
// transform and push the character
characters = characters.append(Character.toUpperCase(ch));
}
// since we were iterating and pushing chars
// from backward direction, reverse the array
// and join it to form a string
characters.reverse();
return characters.toString();
}
}
Written by S. Kumar on May 21st, 2021
3. How do you find two integers in the array such that their sum is 'target'?
This question focuses on the developer's knowledge of loops.
You are given an array 'nums' and an integer target. Your task is to find two integers in the array such that their sum is 'target'. You need to return their indices. It is guaranteed that exactly one solution exists.
/*Example*/
nums = [17, 15, 2, 9] target = 24
expected output:- [1, 3]
explanation:- The sum of integers at indices at 1 and 3 is 24 (15 + 9).
nums = [7, 8, 5, 3, 1] target = 4
expected output:- [3, 4]
explanation:- The sum of integers at indices at 3 and 4 is 4 (3 + 1).
Solution:
We will iterate over the array. We will maintain a map to store the number and their indices. The numbers will be the keys and their indices will be the values of the map.
Let curr be the current number. We will check if target - curr exists in the map, which means we have got our two required numbers and will return their indices.
If target - curr does not exist, we will save curr to the map.
import java.io.*;
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer,
Integer>();
int sol[] = new int[2];
for (int i = 0; i < nums.length; i++) {
int curr = nums[i];
int diff = target - curr;
if (!map.containsValue(diff)) {
map.put(i, curr);
continue;
}
sol[0] = i;
for(int j = 0; j < map.size();j++){
if(map.get(j) == diff){
sol[1] = j;
}
}
}
return sol;
}
}
Time complexity- O(n) where n is the number of elements of the array
Space complexity- O(n)
Written by S. Kumar on May 21st, 2021
4. How do you determine if a string is valid or not?
This interview question focuses on Java methods.
You are given string 'str'. The string consists of characters “(“, “)â€, “{“, “}â€, “[“ and “]â€. Your task is to determine if str is valid or not. A string consisting of valid if it contains:-
◠every opening bracket is closed by a closing bracket of the same type (“(){}[()]†is valid while
“(){[]†is not valid), and
◠the opening and closing brackets are in the correct order (“()[]†is valid but “)(†and “({)}†are
not valid).
/*Example*/
str = “()â€
expected output = true
str = “()[]{}â€
expected output = true
str = “(]â€
expected output = false
str = “({)}â€
expected output = false
Solution:
We will iterate over the passed string. We will use a stack to track the opening brackets. If the current bracket is an opening bracket i.e. one of “(“, “{“ and “[“, we will push it to the stack. If the current bracket is a closing bracket, then:-
â— If the stack is empty, it means there is no matching opening bracket in the stack. So return false.
â— If the stack is not empty. we will pop an opening bracket from the stack. The popped opening bracket and the current closing bracket is of the same type, we will continue with the next bracket. If they are not of the same type, we will return false.
After iterating over all the brackets, if the stack is empty, we return true. If it is not empty, we return false because it means, there are some opening brackets that are not matched yet.
import java.util.*;
class Solution {
static Map<Character, Character> map = new HashMap<Character,
Character>();
static {
map.put('[',']');
map.put('(',')');
map.put('{','}');
}
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
String opens = "({[";
for (int i = 0; i < s.length(); i++) {
if (opens.indexOf(s.charAt(i)) != -1) {
stack.push(s.charAt(i));
continue;
}
if (stack.empty()) {
return false;
}
char ch = stack.pop();
if (!areMatching(ch, s.charAt(i))) {
return false;
}
}
return stack.empty();
}
private boolean areMatching(char opening, char closing) {
return map.get(opening) == closing;
}
}
Time complexity- O(n) where n is the length of string
Space complexity- O(n)
Written by S. Kumar on May 21st, 2021
5. How can you find the third largest number in an array?
This question works with Java methods and loops.
You are given an array of integers. Your task is to find the third-largest number in the array. It is guaranteed that the answer always exists.
/*Example*/
nums = [5, 9, 1, 7, 8]
expected output = 7
Solution:
We will iterate over all the numbers. We will have three variables:- firstMax, secondMax and thirdMax. They all are initialized to -Infinity. Let curr be the current number:-
â— If curr is larger than firstMax, the new value of firstMax will be curr, and the new value of secondMax will be old value firstMax, and the new value of thirdMax will be old value secondMax.
â— If curr is larger than secondMax (and smaller than firstMax), the new value of secondMax will be old value curr, and the new value of thirdMax will be old value secondMax.
â— If curr is larger than thirdMax (and smaller than secondMax), the new value of thirdMax will be the old value curr.
â— If curr is smaller than thirdMax, all values will be unchanged.
class Solution {
public int thirdMax(int[] nums) {
//Using Double as - Infinity does not exist in Integer.
double firstMax = Double.NEGATIVE_INFINITY;
double secondMax = Double.NEGATIVE_INFINITY;
double thirdMax = Double.NEGATIVE_INFINITY;
for (int num : nums) {
if (num > firstMax) {
thirdMax = secondMax;
secondMax = firstMax;
firstMax = num;
} else if (num > secondMax) {
thirdMax = secondMax;
secondMax = num;
} else if (num > thirdMax) {
thirdMax = num;
}
}
return (int) thirdMax;
}
}
Time complexity- O(n) where n is the number of integers in the array
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
6. Find if the array contains a unique number of occurrences for each value in the array or not.
This interview question shows the developer's knowledge of filtering in Java.
You are given an array of integers. Your task is to find if the array contains a unique number of occurrences for each value in the array or not.
/*Example*/
arr = [1, 2, 2, 1, 1, 3]
expected output = true
freq of 1 = 3
freq of 2 = 2
freq of 3 = 1
The frequencies are unique for each value, so we return true.
arr = [1,2]
expected output = false
freq of 1 = 1
freq of 2 = 1
The frequencies are not unique for each value, so we return false.
Solution:
We store the frequencies for each value in a map. The keys of the map will be the integers and the values will be the frequency of those integers. Then we create a set from those frequencies (using map.values()). If the size of the set is equal to the size of the map, it means all frequencies were unique, if the sizes are not equal, it means some frequencies were not unique.
import java.util.*;
class Solution {
public boolean uniqueOccurrences(int[] arr) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int num : arr){
int prevOccurence = 0;
if(map.get(num) != null) prevOccurence = map.get(num);
map.put(num, prevOccurence + 1);
}
Collection<Integer> values = map.values();
HashSet<Integer> set = new HashSet(values);
return map.size() == set.size();
}
}
Time complexity- O(n) where n is the number of integers in the array
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
7. Determine if str1 is a subsequence of str2.
This question tests the developer's ability to work with Java sequences.
You are given two strings str1 and str2. Your task is to find if str1 is a subsequence of str2.
A subsequence of a string is a string that is created from the original by deleting zero or more characters with the order of remaining characters the same as the original string.
So if the original string is “abcdeâ€, the possible subsequences are:
◠“abcdeâ€:- deleting no zero characters.
◠“abdeâ€:- deleting “câ€
◠“bdeâ€:- deleting “a†and “câ€
but these are not valid subsequences-
◠“aebâ€:- the relative order is not the same
◠“cbzâ€:- contains other character “z†which is not in original string
/*Example*/
str1 = “abcâ€, st2 = “ahbgdcâ€
expected output- true
str1 = “axcâ€, st2 = “ahbgdcâ€
expected output- false
Solution:
We will iterate over each character of str1. We will find the index of each character of str1 in str2 starting from the index of the last character in str1. If the found index is -1, we return false, because it does not exist in str2. Otherwise, we continue to the next character of str1. For example:
str1 = “abcâ€, st2 = “ahbgdc
start with the first character of str1 => “aâ€
=> index of “a†in str2 = 0
=> which is not -1
=> continue with next character
=> next character of str1 => “bâ€
=> index of “b†in str2 after index 0 (index of last character “aâ€) = 2
=> which is not -1
=> continue with next character
=> index of “c†in str2 after index 2 (index of last character “bâ€) = 5
=> which is not -1
=> all characters of str1 found in str2 with correct positions
=> return true
Another example:
str1 = “aghâ€, st2 = “ahbgdc
start with the first character of str1 => “aâ€
=> index of “a†in str2 = 0
=> which is not -1
=> continue with next character
=> next character of str1 => “gâ€
=> index of “g†in str2 after index 0 (index of last character “aâ€) = 3
=> which is not -1
=> continue with next character
=> index of “h†in str2 after index 3 (index of last character “gâ€) = -1
=> which is -1
=> return false
One thing to note here is that “h†did exist in str2, but it was before the index “gâ€, and we wanted it after the index “g†which is not the case. So we return -1.
We will use String.indexOf function to find the index of the character in str2. The function takes two arguments:
1. searchValue:- the string/character whose index we want to find
2. fromIndex (optional):- the index at which we want to start the search (default is 0)
class Solution {
public boolean isSubsequence(String s, String t) {
int lastIndex = -1;
// iterate over each character of str1
for(char c : s.toCharArray()) {
// find index of char in str2 starting from index of last character
lastIndex = t.indexOf(c, lastIndex + 1);
if (lastIndex == -1) return false;
}
return true;
}
}
Time complexity- O(m + n)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
8. Find the largest two numbers in an array without sorting them.
This question focuses on knowledge of arrays in Java.
You are given an unsorted array of integers. Your task is to find the two largest elements in the array without sorting them. Return the two integers in the array of size two, the largest at index-0 and the second-largest at index-1.
/*Example*/
Given- [1, 3, 2, 5, 4]
expected output- [5, 4]
Solution:
We will iterate over each number of the given array. We will maintain two variables largest and secondLargest for the largest and the second-largest element seen so far. When we encounter a new number, we check:
â— if it is greater than largest, then the previous value of largest becomes secondLargest, and the new number becomes largest. For example:-
let previously, largest = 10 secondLargest = 7
let the new number is 12 which is greater than largest. So updated values are:-
largest = 12 secondLargest = 10
◠if it is greater than secondLargest (and smaller than largest), then the new number becomes secondLargest. We don’t need to change largest. For example:-
let previously, largest = 10 secondLargest = 7
let the new number is 8 which is greater than secondLargest. So updated values are:-
largest = 10 secondLargest = 8
◠if it is smaller than secondLargest, we don’t need to change anything.
class Solution {
public int[] twoLargest(int[] nums) {
double firstMax = Double.NEGATIVE_INFINITY;
double secondMax = Double.NEGATIVE_INFINITY;
for (int num : nums) {
if (num > firstMax) {
secondMax = firstMax;
firstMax = num;
} else if (num > secondMax) {
secondMax = num;
}
}
return new int[] {(int) firstMax, (int) secondMax};
}
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
9. Find unique vanishing numbers.
This question tests the developer's ability to use Java methods.
You are given an integer n. Your task to generate and return an array consisting of unique integers such that they all add up to 0. You can return any array that satisfies the property.
/*Example*/
Given n = 5
expected output:- [1, 2, -3, 4, -4]
other possible answers:
[0, 1, 2, -1, -2]
[-4, -3, 5, 2, 0] and many more...
Solution:
As we can see, there are many possible ways to generate the array. Some of these are-
â— Fill from left and right with additive identities (x and -x). For example-
for n = 5, [-1, -2, 0, 2, 1]
for n = 6, [-1, -2, -3, 3, 2, 1]
â— Fill n - 1 positive integers, and put minus of sum all those positive integers as nth integer. For example-
for n = 5, [1, 2, 3, 4, -10]
for n = 6, [1, 2, 3, 4, 5, -15]
The second solution seems easier. So we will code it.
class Solution {
static int[] vanishingNumbers(int n) {
int result[] = new int[n];
int sum = 0;
for (int i = 0; i < n - 1; i++) {
result[i] = i + 1;
sum += result[i];
}
result[n - 1] = -sum;
return result;
}
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
10. Create a running sum of a 1-D array.
This question focuses on Java functions.
You are given an array nums of integers. Your task is to find a new array runningSum such that runningSum[i] = sumOf(nums[0], nums[1], …, nums[i]).
/*Example*/
Given nums = [1, 2, 3, 4]
Expected output:- [1, 3, 6, 10]
Explanation:-
runningSum = [1, 1 + 2, 1 + 2 + 3, 1 + 2 + 3 + 4] = [1, 3, 6, 10]
Given nums = [4, 3, 2, 1]
Expected output:- [4, 7, 9, 10]
Explanation:-
runningSum = [4, 4 + 3, 4 + 3 + 2, 4 + 3 + 2 + 1] = [4, 7, 9, 10]
Solution:
We will create a new array runningSum. We will set runningSum[0] = nums[0] because the first element in both the array is the same. Now,
runningSum[i] = sum of all elements in nums from 0 to i
runningSum[i + 1] = sum of all elements in nums from 0 to (i + 1)
= (sum of all elements in nums from 0 to i) + nums[i + 1]
runningSum[i + 1] = runningSum[i] + nums[i + 1]
class Solution {
public int[] runningSum(int[] nums) {
int runningSum[] = new int[nums.length];
runningSum[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
runningSum[i] = nums[i] + runningSum[i - 1];
}
return runningSum;
}
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021
11. Find if the robot returns to its home after given instructions or not.
This question focuses on Java functions.
There is a robot initially at its home- the origin on a 2D plane. It is given some instructions to move to either left or right or up or down. The robot moves the same distance at each instruction in any direction. You are given a string moves consisting of letters “Lâ€, “Râ€, “Uâ€, and “D†corresponding to left, right, up, and down respectively. The string moves tell the series of instructions given to the robot. Your task is to find if the robot returns to its home after these instructions or not.
/*Example*/
Given moves = “LUDRâ€
expected output = true
Given moves = “LLRâ€
expected output = false
Solution:
The solution is quite simple after making an observation. The origin is x = 0 and y = 0. We will store the current coordinate of the robot.
â— For R, the x coordinate increases by one.
â— For L, the x coordinate decreases by one.
â— For U, the y coordinate increases by one.
â— For D, the y coordinate decreases by one.
The robot will be at the origin if and only if the x and y coordinates are both 0 i.e. the robot must be on both the axis to be on origin i.e at point (0, 0).
class Solution {
public boolean judgeCircle(String moves) {
int x = 0;
int y = 0;
for (char ch : moves.toCharArray()) {
switch(ch) {
case 'R':
x++;
break;
case 'L':
x--;
break;
case 'U':
y++;
break;
case 'D':
y--;
break;
}
}
return x == 0 && y == 0;
}
}
Time complexity- O(n)
Space complexity- O(1)
Written by S. Kumar on May 21st, 2021