Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 8

1) How can you count the number of occurrences of a particular character in a

Java/Kotlin String,
and what are some different approaches that can be used to achieve this?

public class CountOccuranceOfChar1


{
public static void main(String args[])
{
String str="AnandGaur";
int i, len;
int counter[] = new int[256];
len = str.length();

for (i = 0; i < len; i++)


{
counter[(int) str.charAt(i)]++;
}
for (i = 0; i < 256; i++)
{
if (counter[i] != 0)
{
System.out.println((char) i + " --> " + counter[i]);
} } } }

2) What is a possible approach to find the most frequently occurring character in a


Java String

public class GFG {


static final int ASCII_SIZE = 256;
static char getMaxOccurringChar(String str)
{
int count[] = new int[ASCII_SIZE];
int len = str.length();
for (int i = 0; i < len; i++)
count[str.charAt(i)]++;
int max = -1; // Initialize max count
char result = ' '; // Initialize result

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


if (max < count[str.charAt(i)]) {
max = count[str.charAt(i)];
result = str.charAt(i);
}
}

return result;
}
public static void main(String[] args)
{
String str = "anan";
System.out.println("Max occurring character is "
+ getMaxOccurringChar(str));
}
}

3) What is an approach to add the individual digits of a given integer in


Java/Kotlin programming,
and how can you implement this solution to calculate the sum of digits for an
integer such as
567 and return the result of 18?

public class SumOfDigitsExample1


{
public static void main(String args[])
{
int number=567, digit, sum = 0;

while(number > 0)
{
digit = number % 10;
sum = sum + digit;
number = number / 10;
}
System.out.println("Sum of Digits: "+sum);
}
}

4) Write a Java/Kotlin program to find the largest subarray in an integer array


that has a sum of 0.
Can you explain your approach to solving this problem and provide a step-by-step
explanation
of your code? How does your program handle edge cases, such as when there is no
subarray
with a sum of 0 or when the input array is empty?
Eg: Input = { 3, 4, -7, 3, 1, 3, 1, -4, -2, -2 }

class GFG {

static void maxSubArraySum(int a[], int size)


{
int max_so_far = Integer.MIN_VALUE,
max_ending_here = 0, start = 0, end = 0, s = 0;

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


max_ending_here += a[i];

if (max_so_far < max_ending_here) {


max_so_far = max_ending_here;
start = s;
end = i;
}

if (max_ending_here < 0) {
max_ending_here = 0;
s = i + 1;
}
}
System.out.println("Maximum contiguous sum is "
+ max_so_far);
System.out.println("Starting index " + start);
System.out.println("Ending index " + end);
}

// Driver code
public static void main(String[] args)
{
int a[] = { 3, 4, 7, 3, 1 };
int n = a.length;
maxSubArraySum(a, n);
}
}

5) Can you provide a program in Java/Kotlin that finds all the subarrays in an
array whose sum is
zero? How does your implementation work? Can you explain the time and space
complexity of
your solution? Are there any optimizations that can be made to improve the
efficiency of your
program

Time Complexity: O(n)


Auxiliary Space: O(1)

6)Write a Java/Kotlin program to find the sum of all the numbers in a given string.
For example, if
the input string is "1ab2d4hj6", the program should output the sum of numbers in
the string,
which is 13.
The program should take a string as input from the user and use regular expressions
to extract
all the numbers from the string. It should then iterate over the extracted numbers
and add them
up to get the final sum. If there are no numbers in the string, the program should
output 0.

import java.io.*;

class GFG {

static int findSum(String str)


{
// A temporary string
String temp = "0";
int sum = 0;

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


char ch = str.charAt(i);

if (Character.isDigit(ch))
temp += ch;
else {
sum += Integer.parseInt(temp);
temp = "0";
}
}
return sum + Integer.parseInt(temp);
}
public static void main(String[] args)
{
String str = "1ab2d4hj6";

System.out.println(findSum(str));
}
}
7) Write a Java/Kotlin program that takes two strings as input and finds the number
of occurrences
of the second string in the first string.
Example:
Input:
String 1: "hello world"
String 2: "l"
Output:
Number of occurrences of "l" in "hello world" is 3

import java.io.*;

class GFG
{
static int count(String a, String b, int m, int n)
{
if ((m == 0 && n == 0) || n == 0)
return 1;

if (m == 0)
return 0;

if (a.charAt(m - 1) == b.charAt(n - 1))


return count(a, b, m - 1, n - 1) +
count(a, b, m - 1, n);
else
return count(a, b, m - 1, n);
}

public static void main (String[] args)


{
String a = "hello world";
String b = "l";
System.out.println( count(a, b, a.length(), b.length())) ;
}
}

8) Write a Java/Kotlin program to find the sum of all the numbers in a given
string. Your program
should take a string as input from the user and then find all the numbers in the
string. It should
then add up all the numbers and print the sum to the console.
Here are some requirements for your program:
The string should be read from the console using the Scanner class.
Your program should use regular expressions to find all the numbers in the string.
The sum of the numbers should be calculated using a loop.
If there are no numbers in the string, your program should print a message saying
so.
Example:
Input: "Hello 123 world 456"
Output: 579

import java.io.*;

class GFG {

static int findSum(String str)


{

String temp = "0";

int sum = 0;

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


char ch = str.charAt(i);

if (Character.isDigit(ch))
temp += ch;

else {

sum += Integer.parseInt(temp);
temp = "0";
}
}

return sum + Integer.parseInt(temp);


}

public static void main(String[] args)


{
// input alphanumeric string
String str = "Hello 123 world 456";

// Function call
System.out.println(findSum(str));
}
}

9). Write a Java/Kotlin program to find all the duplicate elements in an integer
array with less time
complexity.
Example input:
int[] arr = {4, 2, 4, 5, 2, 3, 1, 1, 6, 7, 7};
Expected output:
Duplicate elements in the given array are:
4 2 1 7

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

//Initialize array
int [] arr = new int [] {4, 2, 4, 5, 2, 3, 1, 1, 6, 7, 7};

System.out.println("Duplicate elements in given array: ");

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


for(int j = i + 1; j < arr.length; j++) {
if(arr[i] == arr[j])
System.out.println(arr[j]);
}
}
}
}

Time Complexity: O(N)


Auxiliary Space: O(N)

9)Write a Java/Kotlin program to reverse an array without using any inbuilt


methods.

class ReverseArray {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("Array in reverse order: ");
//Loop through the array in reverse order
for (int i = arr.length-1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}

10) You have been given an integer array and a key integer. Your task is to write a
Java/Kotlin
function that finds the number in the array which has the highest frequency and
replaces it with
the given key integer

class GFG
{

public static int mostFrequent(int[] arr, int n)


{
int maxcount = 0;
int element_having_max_freq = 0;
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}

if (count > maxcount) {


maxcount = count;
element_having_max_freq = arr[i];
}
}

return element_having_max_freq;
}

// Driver program
public static void main(String[] args)
{
int[] arr = { 40, 50, 30, 40, 50, 30, 30 };
int n = arr.length;
System.out.print(mostFrequent(arr, n));
}
}

11) Write a Java/Kotlin program to display the highest prime number.


// Java program to find largest number smaller than
// equal to n with all prime digits.
import java.io.*;
class GFG
{

// check if character is prime


public static boolean isPrime(char c)
{
return (c == '2' || c == '3' || c == '5' || c == '7');
}

// replace with previous prime character


public static void decrease(StringBuilder s, int i)
{
if (s.charAt(i) <= '2')
{

// if 2 erase s[i] and replace next with 7


s.deleteCharAt(i);
s.setCharAt(i, '7');
}
else if (s.charAt(i) == '3')
s.setCharAt(i, '2');
else if (s.charAt(i) <= '5')
s.setCharAt(i, '3');
else if (s.charAt(i) <= '7')
s.setCharAt(i, '5');
else
s.setCharAt(i, '7');

return;
}

public static String primeDigits(StringBuilder s)


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

// find first non prime char


if (!isPrime(s.charAt(i)))
{

// find first char greater than 2


while (i >= 0 && s.charAt(i) <= '2')
i--;

// like 20
if (i < 0)
{
i = 0;
decrease(s, i);
}

// like 7721
else
decrease(s, i);

// replace remaining with 7


for (int j = i + 1; j < s.length(); j++)
s.setCharAt(j, '7');
break;
}
}

return s.toString();
}

// Driver code
public static void main(String[] args)
{
StringBuilder s = new StringBuilder("45");
System.out.println(primeDigits(s));

s = new StringBuilder("1000");
System.out.println(primeDigits(s));

s = new StringBuilder("7721");
System.out.println(primeDigits(s));

s = new StringBuilder("7221");
System.out.println(primeDigits(s));

s = new StringBuilder("74545678912345689748593275897894708927680");
System.out.println(primeDigits(s));
}
}

// This code is contributed by


// sanjeev2552

You might also like