0% found this document useful (0 votes)
28 views8 pages

Count Character Occurrences in Kotlin/Java

The document discusses various approaches to solve string and array problems in Java/Kotlin. It includes problems such as counting character occurrences in a string, finding the most frequent character, calculating digit sum of an integer, finding the largest subarray with sum 0, and more. For each problem, it provides the problem statement, sample code to solve it and sometimes explanations of the approach and time/space complexity.

Uploaded by

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

Count Character Occurrences in Kotlin/Java

The document discusses various approaches to solve string and array problems in Java/Kotlin. It includes problems such as counting character occurrences in a string, finding the most frequent character, calculating digit sum of an integer, finding the largest subarray with sum 0, and more. For each problem, it provides the problem statement, sample code to solve it and sometimes explanations of the approach and time/space complexity.

Uploaded by

Anand Gaur
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

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 = [Link]();

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


{
counter[(int) [Link](i)]++;
}
for (i = 0; i < 256; i++)
{
if (counter[i] != 0)
{
[Link]((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 = [Link]();
for (int i = 0; i < len; i++)
count[[Link](i)]++;
int max = -1; // Initialize max count
char result = ' '; // Initialize result

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


if (max < count[[Link](i)]) {
max = count[[Link](i)];
result = [Link](i);
}
}

return result;
}
public static void main(String[] args)
{
String str = "anan";
[Link]("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;
}
[Link]("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;
}
}
[Link]("Maximum contiguous sum is "
+ max_so_far);
[Link]("Starting index " + start);
[Link]("Ending index " + end);
}

// Driver code
public static void main(String[] args)
{
int a[] = { 3, 4, 7, 3, 1 };
int n = [Link];
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 [Link].*;

class GFG {

static int findSum(String str)


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

for (int i = 0; i < [Link](); i++) {


char ch = [Link](i);

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

[Link](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 [Link].*;

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 ([Link](m - 1) == [Link](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";
[Link]( count(a, b, [Link](), [Link]())) ;
}
}

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 [Link].*;

class GFG {

static int findSum(String str)


{

String temp = "0";

int sum = 0;

for (int i = 0; i < [Link](); i++) {


char ch = [Link](i);

if ([Link](ch))
temp += ch;

else {

sum += [Link](temp);
temp = "0";
}
}

return sum + [Link](temp);


}

public static void main(String[] args)


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

// Function call
[Link](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};

[Link]("Duplicate elements in given array: ");

for(int i = 0; i < [Link]; i++) {


for(int j = i + 1; j < [Link]; j++) {
if(arr[i] == arr[j])
[Link](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};
[Link]("Original array: ");
for (int i = 0; i < [Link]; i++) {
[Link](arr[i] + " ");
}
[Link]();
[Link]("Array in reverse order: ");
//Loop through the array in reverse order
for (int i = [Link]-1; i >= 0; i--) {
[Link](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 = [Link];
[Link](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 [Link].*;
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 ([Link](i) <= '2')
{

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


[Link](i);
[Link](i, '7');
}
else if ([Link](i) == '3')
[Link](i, '2');
else if ([Link](i) <= '5')
[Link](i, '3');
else if ([Link](i) <= '7')
[Link](i, '5');
else
[Link](i, '7');

return;
}

public static String primeDigits(StringBuilder s)


{
for (int i = 0; i < [Link](); i++)
{

// find first non prime char


if (!isPrime([Link](i)))
{

// find first char greater than 2


while (i >= 0 && [Link](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 < [Link](); j++)
[Link](j, '7');
break;
}
}

return [Link]();
}

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

s = new StringBuilder("1000");
[Link](primeDigits(s));

s = new StringBuilder("7721");
[Link](primeDigits(s));

s = new StringBuilder("7221");
[Link](primeDigits(s));

s = new StringBuilder("74545678912345689748593275897894708927680");
[Link](primeDigits(s));
}
}

// This code is contributed by


// sanjeev2552

Common questions

Powered by AI

To count the frequency of each character in a string, you can use an array to store the counts corresponding to each character's ASCII value. Initialize an integer array of size 256 (to cover all ASCII characters) with zeros. Loop through each character of the string, convert it to its ASCII value using `str.charAt(i)`, and increment the respective index in the array. Finally, loop through the array to print characters with non-zero counts .

To reverse an integer array without inbuilt methods, use a two-pointer approach. Initialize one pointer at the start and another at the end of the array. Swap elements at these pointers and increment the start pointer while decrementing the end pointer, continuing until they meet. This method is efficient with a time complexity of O(n) and does not use additional space .

The recursive approach to find occurrences of a substring within another string involves base cases where either the main string or substring is exhausted. Check if the current characters of both strings match and continue recursively by reducing the lengths of either or both strings. This method explores all possible ways the substring can occur, counting valid configurations recursively .

To compute the sum of the digits in an integer, initialize a sum variable to zero. Repeatedly extract the last digit using modulus 10 and add it to the sum. Then divide the number by 10 to remove the last digit and repeat until the integer becomes zero. The accumulated sum will be the result .

To find subarrays with zero sum efficiently, use a HashMap to store the cumulative sum of elements at each index. As you iterate through the array, calculate the cumulative sum. If this sum repeats (exists in the HashMap), it indicates that the subarray between these indices sums to zero. This approach allows finding zero-sum subarrays in O(n) time and consumes O(n) space .

To determine the largest number with all prime digits, iterate over the digits of the given number. Replace non-prime digits with the largest prime digit smaller than themselves. Implement a check that adjusts each digit greedily based on adjacent digits to form the largest possible number while ensuring all digits remain prime. This process is iterative and requires careful handling of digits .

An optimized approach to find duplicates involves using a HashSet to track seen elements. As you iterate through the array, check if each element is already in the set. If it is, it's a duplicate; if not, add it to the set. This approach runs in O(n) time due to HashSet operations being nearly constant and uses O(n) auxiliary space .

First, calculate the frequency of each element using a HashMap where keys are elements and values are their counts. Identify the element with the maximum frequency. Iterate through the array again and replace every occurrence of this element with the given key integer. This ensures the array is modified based on frequency analysis .

To determine the most frequently occurring character, first create an array to count occurrences of each character based on their ASCII values. As you iterate over the string, increment the count for each character's ASCII index. Maintain a variable to track the maximum count and a character variable to store the character corresponding to the maximum count. Iterate again to update the maximum count and result character if a higher frequency is found during the traversal .

In Java, you can use regular expressions to extract numbers from a string. Utilize the `Pattern` and `Matcher` classes to identify sequences of digits. As you iterate through these matches, convert each substring to an integer and add to a cumulative sum. This method efficiently isolates and processes numbers interspersed in text .

You might also like