Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Every tech company is looking for talented minds who can solve complex problems. Often people learn some programming language but don’t focus on solving problems. Also, there are people who want to solve some really good standard problems but get confused among ample problems out there. So, Worry not! Coding ninjas got your back!
In this blog, we will solve some best and most frequently asked Java programming challenges. So without any further wait, let’s start learning!
Anagrams
Problem Statement
Given two strings. Check whether both the strings are anagrams of each other or not.
[ Anagram strings are those strings that have the same characters, only the order of characters may be different ]
One method to solve this problem is sorting both strings and checking whether both are equal or not. But the sorting operation would take O(n*log(n)) time. So instead of sorting, we will count the frequency of characters, and if the frequency is the same, then both will be anagrams of each other.
Code
import java.util.*;
class Solution {
// Function to check whether anagram strings
public static boolean CheckAnagram(String str1, String str2) {
//Comparing the lengths
if (str1.length() != str2.length()) {
return false ;
}
//Creating and initialising arrays
int count1[] = new int[256];
Arrays.fill(count1, 0);
int count2[] = new int[256];
Arrays.fill(count2, 0);
int i;
for (i = 0; i < str1.length() && i < str2.length(); i++) {
count1[str1.charAt(i)]++;
count2[str2.charAt(i)]++;
}
// Compare count arrays
for (i = 0; i < 256; i++) {
if (count1[i] != count2[i]) {
return false;
}
}
return true;
}
//Main starts here
public static void main(String args[]) {
String str1 = "coding";
String str2 = "ingodc";
// Function call
if (CheckAnagram(str1, str2)) {
System.out.println("Strings are anagrams");
}
else{
System.out.println("Strings are not anagrams");
}
}
}
You can also try this code with Online Java Compiler
In the above example, we created a checkAnagram() function and passed both strings to it. After that, we created two arrays of size 256 to store the frequency of all possible characters of the string. Once we had iterated, we checked the frequency of characters of both strings and likewise returned the result.
You are given a string. Your task is to check whether the given string is palindrome or not. A string is said to be a palindrome if the reverse of the string is the same as the given string.
Input
string = 'LeveL'
string = 'coding'
Output
Yes
No
Approach
This problem can be solved by various methods, but we will focus on solving it using two pointer approach. Here, one pointer will point at the beginning of the string and will move forward. At the same time, another pointer will point at the end of the string and will move backwards. We will compare each character while iterating and likewise return the result.
Code
class Solution {
//Function to check palindrome strings
public static boolean IsPalindrome(String s, int n) {
int start = 0, end = n-1;
while(start<=end) {
//Comparing end characters
if(s.charAt(start) != s.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}
public static void main(String[] args) {
String s= "LeveL";
int n = s.length();
if(IsPalindrome(s, n) == true) {
System.out.println("'"+ s + "' is palindrome");
}
else {
System.out.println("'"+ s+ "' is not palindrome");
}
}
}
You can also try this code with Online Java Compiler
In the above example, we created a function IsPalindrome() to check whether a string is a palindrome or not. We also created two variables which point at the beginning and at the end of the string. After that, we iterated over the string and compared the characters at opposite ends. If the characters do not matches, we will return true. Otherwise, we will iterate till the start variable becomes greater than the end variable.
Time Complexity: O(n)
Space Complexity: O(1)
Leaders in an Array
Problem Statement
Given a sequence of numbers. Find all leaders in the sequence. An element is called a leader if it is strictly greater than all elements to its right side.
Input
arr[] = {23, 22, 24, 9, 10}
Output
10, 24
Approach
We will start iterating from the last position element. The last index element is itself a leader as it has no element to its right, so we will print it and iterate all the way till we reach the first index element. While iterating, we will keep a variable to store the maximum value so far and print and update it whenever we encounter a bigger element.
Code
class Solution {
public static void PrintLeaders(int arr[], int N) {
//Storing the maximum element so far
int Max_So_Far = arr[N - 1];
// Printing the last element
System.out.print(Max_So_Far + " ");
//Iterating and checking for the next max value
for (int i = N - 2; i >= 0; i--) {
if (Max_So_Far < arr[i]) {
Max_So_Far = arr[i];
System.out.print(Max_So_Far + " ");
}
}
}
public static void main(String[] args) {
//Creating the array
int arr[] = new int[] {23, 22, 24, 9, 10};
int n = arr.length;
//Calling the function
PrintLeaders(arr, n);
}
}
You can also try this code with Online Java Compiler
In the above example, we called the PrintLeader() function to print all the leaders in the given array. We created a variable Max_So_Far to store the maximum element till now and iterated the array backwards, and simultaneously updated the maximum element. Once we encounter a new maximum element, we update the max value and print it.
Time Complexity: O(n)
Space Complexity: O(1)
Stock Buy and Sell
Problem Statement
You are given an array of integers, prices where prices[i] is the price of a given stock on an ith day. You want to maximise the profit by choosing a single day to buy one stock and a different day to sell that stock. Return themaximum profit you can get from this transaction.
Input
prices = [7, 1, 5, 4, 3, 6]
Output
5
Explanation
Here, we will purchase the stock on 2nd day when the price is 1 and sell it on the sixth day wherein the price is 6. Thus, profit = 6 - 1 = 5.
Approach
We will iterate and store the minimum cost at which we can buy the stock on that particular day. Whenever we encounter a smaller cost, we will update the minimum cost and find the maximum profit so far.
Code
public class Solution{
//Function to calculate maximum profit
public static int findMaxProfit(int[] prices) {
//Initialising variables
int minCost = Integer.MAX_VALUE;
int profit = 0;
for(int i = 0; i < prices.length; i++) {
minCost = Math.min(minCost, prices[i]);
profit = Math.max(profit, prices[i] - minCost);
}
return profit;
}
//Main starts here
public static void main(String[] args) {
System.out.print("Maximum profit is: ");
//Prices array
int[] prices = {7, 1, 5, 4, 3, 6};
//Printing result
System.out.println(findMaxProfit(prices));
}
}
You can also try this code with Online Java Compiler
In the above example, we initialised a variable minCost with the maximum integer value to store the stock's minimum cost. After that, we iterated over the prices, and whenever we found any lower-price stock, we updated the variable minCost and calculated the profit so far. We returned the maximum profit possible after iterating over the complete array.
Time Complexity: O(n)
Space Complexity: O(1)
Assign Mice to Holes
Problem Statement
There are n mice and n holes in a straight line. Each hole can only accommodate only a single mouse. A mouse can stay at his position (x), move one step to the right (x+1), or move a step to the left(x-1). Any of these moves will take 1 minute. Your task is to assign mice to holes such that the time when the last mouse gets inside the hole is minimised.
Input
Position of mice = [3, -3, 2]
Position of holes = [3, 0, 4]
Output
3
Explanation
The answer would be 3 because:
Assign the mouse at x=-3 to hole at position x = 0: Time = 3
Assign the mouse at x = 2 to hole at position x= 4: Time = 2
Assign the mouse at x = 3 to hole at position x = 3: time = 0
Thus, after 3 minutes, all the mice will be in holes.
Approach
We can solve this problem using a greedy strategy. We will sort the positions of mice and holes and put every mouse to its corresponding nearest hole to minimise the time. After that, we will find the maximum value of the absolute difference between the ith hole and mouse positions, which would be our final output.
Code
import java.util.*;
class Solution {
//Function to calculate minimum time taken
public static int MaxTimeTaken(ArrayList<Integer> mice, ArrayList<Integer> holes) {
//Checking the size of the list
if (mice.size( ) != holes.size( )) {
return -1 ;
}
// Sort the positions
Collections.sort(mice);
Collections.sort(holes);
//finding the max difference between ith mice and hole
int max_time = 0;
//Iterating over the list
for (int i=0; i<mice.size(); i++) {
if (max_time < Math.abs(mice.get(i)-holes.get(i))) {
max_time = Math.abs(mice.get(i)-holes.get(i));
}
}
//Returning the max value of time
return Math.abs(max_time);
}
//Main function start here
public static void main(String[] args) {
ArrayList<Integer> mice = new ArrayList<Integer>();
mice.add(3);
mice.add(-3);
mice.add(2);
ArrayList<Integer> holes= new ArrayList<Integer>();
holes.add(3);
holes.add(0);
holes.add(4);
System.out.println("The minimum time in which every mouse is in the hole is: "+ MaxTimeTaken(mice, holes));
}
}
You can also try this code with Online Java Compiler
In the above example, we create and pass the argument to the function MaxTimeTaken, which would calculate the minimum time. We sorted both the list using the Collections.sort() method. After that, we iterated over both lists and calculated the maximum absolute difference between the corresponding hole position and mouse position. Once found, we returned the maximum value, which is the minimum time taken to place all the mice.
The programming challenges are the coding problems given by the interviewer to test the problem-solving skills of the candidate.
How to solve a programming challenge?
To solve a challenge, you need to understand the problem first. Next, you need to come up with the best approach for the problem and then code it.
What is problem-solving?
Problem-solving is the process of understanding the problem, finding various approaches to solve it and choosing the best possible approach.
Is Java more hard compared to Python?
Yes, Java is more difficult to master than Python, as it uses explicit typing and more concise syntax.
Conclusion
This article discusses some most asked Java programming challenges. We discussed various coding questions with their best approach. We hope this blog has helped you enhance your knowledge of Java programming challenges. If you want to learn more, then check out our articles.