0% found this document useful (0 votes)
15 views

JAVA

The document discusses Java code snippets for solving problems related to decimal to hexadecimal conversion, calculating the sum of a series, asteroid collisions, longest valid parentheses, character decoding, and regular expression matching. It provides the full code solution for each problem in Java.

Uploaded by

rajputakshay8940
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)
15 views

JAVA

The document discusses Java code snippets for solving problems related to decimal to hexadecimal conversion, calculating the sum of a series, asteroid collisions, longest valid parentheses, character decoding, and regular expression matching. It provides the full code solution for each problem in Java.

Uploaded by

rajputakshay8940
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/ 21

JAVA

Q1. Decimal to Hexa-Decimal ConversioN


SOLUTION:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Solution {
public String decimalToHexadecimal(int decimal) {
// your code here
StringBuilder hexadecimal = new StringBuilder();
while (decimal > 0) {
int remainder = decimal % 16;
char digit;
if (remainder < 10) {
digit = (char) ('0' + remainder);
} else {
digit = (char) ('A' + (remainder - 10));
}
hexadecimal.insert(0, digit);
decimal /= 16;
}
return hexadecimal.toString();
}
}

public class Main {


Editstatic
public with the Docs
void app
main(String[] args) throws IOException {
Make tweaks, leave br
BufferedReader comments, and share
= new BufferedReader(newtheInputStreamReader(System.in));
with others to edit at same time.
int decimal = Integer.parseInt(br.readLine().trim());
Solution solution = GET
NO THANKS new THE
Solution();
APP
String hexadecimal = solution.decimalToHexadecimal(decimal);
System.out.println(hexadecimal);
}
}
:
Q2. SUM OF SERIES
SOLUTION
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Solution {
//your solution here
public int sumOfSeries(int n) {
int sum = 0;
int currentTerm = 0;
for (int i = 1; i <= n; i++) {
currentTerm = constructTerm(i); // Construct the current term
sum += currentTerm; // Add the current term to the sum
}
return sum;
}

// Helper method to construct each term of the series


private int constructTerm(int num) {
int term = 0;
for (int i = 0; i < num; i++) {
term = term * 10 + num;
}
return term;
}
}

public class Main {


public static void main(String[] args) throws IOException {
BufferedReader br
= new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
Solution solution = new Solution();
int result = solution.sumOfSeries(n);
System.out.println(result);
}
}

Q3. The Ram and Ravan Arrow War


SOLUTION:
:
import java.util.Scanner;
import java.util.Stack;

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

int n = sc.nextInt();
int arr[] = new int[n];

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


arr[i] = sc.nextInt();
}

Solution sol = new Solution();


int res[] = sol.asteroidCollision(arr);
if(res.length == 0){
System.out.println("-1");
}
else{
for (int i = 0; i < res.length; i++) {
System.out.print(res[i]+" ");
}
}
sc.close();

}
}
class Solution {
public int[] asteroidCollision(int[] asteroids) {
// Write Code here
Stack<Integer> stack = new Stack<>();

for (int asteroid : asteroids) {


if (stack.isEmpty() || asteroid > 0) {
stack.push(asteroid);
} else {

while (!stack.isEmpty() && stack.peek() > 0 && stack.peek() < Math.abs(ast


eroid)) {
stack.pop();
}
if (stack.isEmpty() || stack.peek() < 0) {
stack.push(asteroid);
} else if (stack.peek() == Math.abs(asteroid)) {
:
stack.pop();
}
}
}

int[] result = new int[stack.size()];


for (int i = result.length - 1; i >= 0; i--) {
result[i] = stack.pop();
}

return result;
}
}

Q4. Longest Valid Parentheses


SOLUTION
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

class Solution {
public int longestValidParentheses(String s) {
//write code here
int maxLen = 0;
Stack<Integer> stack = new Stack<>();
stack.push(-1); // Initial value to handle edge cases

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


char c = s.charAt(i);
if (c == '(') {
stack.push(i);
} else {
stack.pop();
if (stack.isEmpty()) {
stack.push(i); // Resetting the starting index for
next valid substring
} else {
maxLen = Math.max(maxLen, i - stack.peek()); //
Calculate the length of the current valid substring
}
}
:
}

return maxLen;
}
}

public class Main {


public static void main(String[] args) throws IOException {
BufferedReader br
= new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine().trim();
Solution solution = new Solution();
int result = solution.longestValidParentheses(input);
System.out.println(result);
}
}

Q5. Character Decoding


SOLUTION
import java.util.*;
import java.io.*;
class Solution {
public int numDecodings(String s) {
//your code here
if (s == null || s.isEmpty() || s.charAt(0) == '0') {
return 0;
}

// Initialize an array to store the number of ways to decode


substrings
int[] dp = new int[s.length() + 1];
dp[0] = 1; // Base case: an empty string has one decoding
dp[1] = 1; // Base case: a string of length 1 has one decoding

// Loop through the string starting from the second character


for (int i = 2; i <= s.length(); i++) {
// Check if the current character is '0'
if (s.charAt(i - 1) == '0') {
// If the current character is '0', it cannot be mapped to
a letter on its own,
// so we need to check if it forms a valid pair with the
previous character
// If not, the decoding is invalid, return 0
:
if (s.charAt(i - 2) != '1' && s.charAt(i - 2) != '2') {
return 0;
}
// If the current character forms a valid pair with the
previous character,
// update the number of ways to decode the current
substring
dp[i] = dp[i - 2];
} else {
// If the current character is not '0', it can be mapped
to a letter on its own
// Check if the previous character and the current
character form a valid pair
int twoDigit = Integer.parseInt(s.substring(i - 2, i));
if (twoDigit >= 10 && twoDigit <= 26) {
// If they form a valid pair, update the number of
ways to decode the current substring
dp[i] += dp[i - 2];
}
// Update the number of ways to decode the current
substring
dp[i] += dp[i - 1];
}
}

// Return the number of ways to decode the entire string


return dp[s.length()];
}
}

public class Main {


public static void main(String[] args) throws IOException {
BufferedReader br
= new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine().trim();

Solution solution = new Solution();


int result = solution.numDecodings(s);
System.out.println(result);
}
}
:
Q6. Regular Expression Matcher
SOLUTION
import java.util.*;
import java.io.*;
class Solution {
public boolean isMatch(String text, String pattern) {
// your code here
if (pattern.isEmpty()) {
return text.isEmpty();
}

// Check if the first characters of text and pattern match


boolean firstMatch
= !text.isEmpty() && (pattern.charAt(0) == text.charAt(0) || pattern.charA
t(0) == '.');

// Check if the pattern has a '*' after the second character


if (pattern.length() >= 2 && pattern.charAt(1) == '*') {
// Recursive case: if the pattern has a '*' after the second
character
// Check if either we skip the '*' and its preceding character
in the pattern, or
// if the first characters match and we move to the next
character in the text
return (isMatch(text, pattern.substring(2)) || (firstMatch
&& isMatch(text.substring(1), pattern)));
} else {
// Recursive case: if the pattern does not have a '*' after
the second character
// Check if the first characters match and recursively match
the rest of the text and pattern
return firstMatch
&& isMatch(text.substring(1), pattern.substring(1));
}
}
}

public class Main {


public static void main(String[] args) throws IOException {
BufferedReader br
= new BufferedReader(new InputStreamReader(System.in));
:
String text = br.readLine().trim();
String pattern = br.readLine().trim();

Solution solution = new Solution();

boolean result = solution.isMatch(text, pattern);


System.out.println(result ? "true" : "false");
}
}

Q7. Product of All Elements from Array Except the


Current One.
SOLUTION
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

int n = sc.nextInt();
int arr[] = new int[n];

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


arr[i] = sc.nextInt();
}

Solution sol = new Solution();


int res[] = sol.productExceptSelf(arr);
if(res.length == 0){
System.out.println("-1");
}
else{
for (int i = 0; i < res.length; i++) {
System.out.print(res[i]+" ");
}
}
sc.close();

}
}
class Solution {
public int[] productExceptSelf(int[] nums) {
// write code here
:
int n = nums.length;

// Initialize arrays to store prefix and suffix products


int[] prefixProducts = new int[n];
int[] suffixProducts = new int[n];

// Calculate prefix products


prefixProducts[0] = 1;
for (int i = 1; i < n; i++) {
prefixProducts[i] = prefixProducts[i - 1] * nums[i - 1];
}

// Calculate suffix products


suffixProducts[n - 1] = 1;
for (int i = n - 2; i >= 0; i--) {
suffixProducts[i] = suffixProducts[i + 1] * nums[i + 1];
}

// Calculate product except self using prefix and suffix products


int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = prefixProducts[i] * suffixProducts[i];
}

return result;
}
}

Q8.
Print all possible expressions that
evaluate to a target
SOLUTION
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

class Solution {

static ArrayList<String> getExpressions(String input, int target) {


//Write Code Here
:
ArrayList<String> result = new ArrayList<>();
if (input == null || input.length() == 0) {
return result;
}
helper(input, target, 0, "", 0, 0, result);
return result;
}
static void helper(String input, int target, int position, String
currentExpression, long currentVal, long last, ArrayList<String> result) {
if (position == input.length()) {
if (currentVal == target) {
result.add(currentExpression);
}
return;
}
for (int i = position; i < input.length(); i++) {
if (i != position && input.charAt(position) == '0') {
break; // Avoiding numbers with leading zeroes
}
long currentNum = Long.parseLong(input.substring(position, i
+ 1));
if (position == 0) {
helper(input, target, i
+ 1, "" + currentNum, currentNum, currentNum, result);
} else {
helper(input, target, i + 1, currentExpression
+ "+" + currentNum, currentVal + currentNum, currentNum, result);
helper(input, target, i + 1, currentExpression + "-
" + currentNum, currentVal - currentNum, -currentNum, result);
helper(input, target, i + 1, currentExpression
+ "*" + currentNum, currentVal - last + last * currentNum, last
* currentNum, result);
}
}
}
}

public class Main {


public static void main(String[] args) throws IOException {
BufferedReader br
= new BufferedReader(new InputStreamReader(System.in));

String[] input = br.readLine().trim().split("\\s+");


String numStr = input[0];
int target = Integer.parseInt(input[1]);
:
ArrayList<String> res = Solution.getExpressions(numStr, target);
if (res.isEmpty()) {
System.out.println("No expressions evaluate to the target.");
} else {

for (String expr : res) {


System.out.println(expr);
}
}
}
}

Q9. Josphus Problem


SOLUTION
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Solution {
static int josephus(int n, int k) {
//Write Your Code Here
if (n == 1)
return 0;
else
return (josephus(n - 1, k) + k) % n;
}
}

public class Main {


public static void main(String[] args) throws IOException {
BufferedReader br
= new BufferedReader(new InputStreamReader(System.in));

String[] inputs = br.readLine().trim().split("\\s+");


int n = Integer.parseInt(inputs[0]); // Number of people
int k = Integer.parseInt(inputs[1]); // Killing interval

int result = Solution.josephus(n, k);


System.out.println(result + 1);
}
}
:
Q10.Longest Subarray Length
SOLUTION
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Solution {
int longestLength(int arr[], int n) {
// Initialize variables to store the starting and ending indices of
the current subarray
int start = 0;
int end = n - 1;
// Initialize variable to store the longest length found
int longest = 0;

// Iterate through the array to find the longest subarray length


while (start < n && end >= 0) {
// If the first and last elements are the same, calculate the
length of the subarray
if (arr[start] == arr[end]) {
int length = end - start + 1;
// Update the longest length if necessary
longest = Math.max(longest, length);
}
// Move to the next subarray
start++;
end--;
}

return longest;
}
}

public class Main {


public static void main(String[] args) throws IOException {
BufferedReader br
= new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim()); // Size of the
array
String[] input = br.readLine().trim().split(" "); // Input array
elements as strings

int[] arr = new int[n]; // Initialize array

// Convert input strings to integers and store them in the array


:
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(input[i]);
}

// Create an object of the Solution class


Solution solution = new Solution();

// Find and print the longest subarray length


int length = solution.longestLength(arr, n);
System.out.println(length);
}
}

Q11.
Maximum Rectangular Area in a
Histogram
SOLUTION
//{ Driver Code Starts
import java.util.*;
import java.io.*;
import java.util.Stack;
class Solution
{
//Function to find largest rectangular area possible in a given
histogram.
public int getMaxArea(int hist[])
{
// your code here
Stack<Integer> stack = new Stack<>();
int maxArea = 0;
int i = 0;
while (i < hist.length) {
if (stack.isEmpty() || hist[stack.peek()] <= hist[i]) {
stack.push(i++);
} else {
int top = stack.pop();
int area = hist[top] * (stack.isEmpty() ? i : i
- stack.peek() - 1);
maxArea = Math.max(maxArea, area);
}
:
}
while (!stack.isEmpty()) {
int top = stack.pop();
int area = hist[top] * (stack.isEmpty() ? i : i
- stack.peek() - 1);
maxArea = Math.max(maxArea, area);
}
return maxArea;

}
}

public class Main {

public static void main (String[] args) throws IOException {


BufferedReader br
= new BufferedReader(new InputStreamReader(System.in));

int n = Integer.parseInt(br.readLine().trim());
String inputLine[] = br.readLine().trim().split(" ");
int[] arr = new int[n];
for(int i=0; i<n; i++)arr[i]=Integer.parseInt(inputLine[i]);

Solution sol = new Solution();

System.out.println(sol.getMaxArea(arr));

}
}

Q12. Count the Reversals


SOLUTION
import java.util.*;
import java.util.Stack;
class Main
{
public static void main (String[] args)
{
:
Scanner sc = new Scanner(System.in);
String s = sc.next ();
System.out.println (new Solution().countRev (s));
sc.close();
}
}

class Solution
{
int countRev (String input)
{
// your code here
int n = input.length();
if (n % 2 != 0) {
return -1; // If the length is odd, it's not possible to
balance the string
}

Stack<Character> stack = new Stack<>();


int reversalCount = 0;

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


char ch = input.charAt(i);
if (ch == '{') {
stack.push(ch);
} else if (ch == '}') {
if (!stack.isEmpty() && stack.peek() == '{') {
stack.pop(); // Matched with an opening bracket
} else {
stack.push(ch); // Unmatched closing bracket, needs
reversal
}
}
}

// Count the remaining unmatched opening and closing brackets in


the stack
int unmatchedOpen = 0;
int unmatchedClose = 0;
while (!stack.isEmpty()) {
char top = stack.pop();
if (top == '{') {
unmatchedOpen++;
} else {
unmatchedClose++;
:
}
}

// Calculate the total number of reversals required


reversalCount = (unmatchedOpen + 1) / 2 + (unmatchedClose
+ 1) / 2;

return reversalCount;
}
}

Q13. Number To String


SOLUTION
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class NumberToWords {
private static final String[] words
= {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine"};
public static String convertNumberToWords(int number) {
//You code here
if (number == 0) {
return "";
}
int digit = number % 10;
return convertNumberToWords(number / 10) + words[digit] + " ";

public class Main {


public static void main(String[] args) throws IOException {
BufferedReader br
= new BufferedReader(new InputStreamReader(System.in));
int number = Integer.parseInt(br.readLine().trim());
String result = NumberToWords.convertNumberToWords(number);
System.out.println(result);
}
}
:
Q14. Sum of Product of Digits
SOLUTION
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class DigitProductSum {

public static int sumOfProductOfDigits(int n1, int n2){


// your code here
if (n1 == 0 || n2 == 0) {
return 0;
}
int digit1 = n1 % 10;
int digit2 = n2 % 10;
return (digit1 * digit2) + sumOfProductOfDigits(n1 / 10, n2 / 10);
}
}

public class Main {


public static void main(String[] args) throws IOException {
BufferedReader br
= new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().trim().split(" ");
int n1 = Integer.parseInt(input[0]);
int n2 = Integer.parseInt(input[1]);
int result = DigitProductSum.sumOfProductOfDigits(n1, n2);
System.out.println(result);
}
}

Q15. Swap First and Last Digit


SOLUTION
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Solution {
public int swapFirstAndLastDigit(int num) {
:
// Write your code here
String numStr = Integer.toString(num);

// Check if the number has more than one digit


if (numStr.length() > 1) {
// Swap the first and last characters
char[] numChars = numStr.toCharArray();
char temp = numChars[0];
numChars[0] = numChars[numChars.length - 1];
numChars[numChars.length - 1] = temp;
// Convert the modified string back to an integer
return Integer.parseInt(new String(numChars));
}

// If the number has only one digit, no swapping is needed


return num;
}
}

public class Main {


public static void main(String[] args) throws IOException {
BufferedReader br
= new BufferedReader(new InputStreamReader(System.in));

int num = Integer.parseInt(br.readLine().trim());

Solution sol = new Solution();


int result = sol.swapFirstAndLastDigit(num);
System.out.println(result);
}
}

Q16. Add Strings


SOLUTION
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class TwoSumWithOutParseInt {

static int parseInt(String num) {


//Start Writting Your Code
:
return parseIntHelper(num, num.length() - 1);
}
static int parseIntHelper(String num, int index) {
// Base case: if the index is less than 0, return 0
if (index < 0) {
return 0;
}

// Get the integer value of the current character


int digit = num.charAt(index) - '0';

// Recursive call to handle the rest of the string


int remainingSum = parseIntHelper(num, index - 1);

// Calculate the sum and return it


return digit + remainingSum * 10;
}
}

public class Main {


public static void main(String[] args) throws IOException {
BufferedReader br
= new BufferedReader(new InputStreamReader(System.in));
String num1 = br.readLine().trim();
String num2 = br.readLine().trim();
int sum
= TwoSumWithOutParseInt.parseInt(num1) + TwoSumWithOutParseInt.parseInt(nu
m2);
System.out.println(sum);
}
}

Q17.Seed Number
SOLUTION
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Solution {
public boolean isSeed(int x, int y) {
int sum1=0;
int sum=0;
int z = x;
while(x!=0)
{
:
int r = x % 10;
sum1 = sum1 + r;
x = x/10;
}
sum = z * sum1;

if(sum == y)
{
return true;
}
return false;

}
}

public class Main {


public static void main(String[] args) throws IOException {
BufferedReader br
= new BufferedReader(new InputStreamReader(System.in));
int x = Integer.parseInt(br.readLine().trim());
int y = Integer.parseInt(br.readLine().trim());
Solution solution = new Solution();
boolean isSeed = solution.isSeed(x, y);
if (isSeed)
System.out.println("Yes");
else
System.out.println("No");
}
}

18. SandGlass Pattern


Solution
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Solution {
public void printSandGlass(int height) {
//Your code here
for (int i = 0; i <= height - 1; i++) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
:
for (int k = i; k <= height - 1; k++) {
System.out.print("* ");
}
System.out.println();
}

for (int i = height - 1; i >= 0; i--) {


for (int j = 0; j < i; j++) {
System.out.print(" ");
}
for (int k = i; k <= height - 1; k++) {
System.out.print("* ");
}
System.out.println();
}
}
}

public class Main {


public static void main(String[] args) throws IOException {
BufferedReader br
= new BufferedReader(new InputStreamReader(System.in));
int height = Integer.parseInt(br.readLine().trim());

Solution solution = new Solution();


solution.printSandGlass(height);
}
}

19.
:

You might also like