[Go to site: main page, start]

0% found this document useful (0 votes)
22 views5 pages

Java Recursion and String Array Questions

The document contains a series of Java practice questions focused on recursion, strings, and arrays. Each section includes problems of varying difficulty, complete with explanations and example code. Topics covered include printing numbers, summing digits, reversing strings, checking for palindromes, and manipulating arrays.
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)
22 views5 pages

Java Recursion and String Array Questions

The document contains a series of Java practice questions focused on recursion, strings, and arrays. Each section includes problems of varying difficulty, complete with explanations and example code. Topics covered include printing numbers, summing digits, reversing strings, checking for palindromes, and manipulating arrays.
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

Java Practice Questions - Recursion, Strings &

Arrays

Recursion

Q1 [Easy] Print numbers from 1 to N using recursion


Explanation: Each recursive call prints the next number until n==0.
class RecQ1 {
static void printNumbers(int n) {
if(n == 0) return;
printNumbers(n-1);
[Link](n + " ");
}
public static void main(String[] args) {
printNumbers(5); // Output: 1 2 3 4 5
}
}

Q2 [Easy-Medium] Sum of digits of a number using recursion


Explanation: Split number into last digit + sum of remaining.
class RecQ2 {
static int sumDigits(int n) {
if(n == 0) return 0;
return (n % 10) + sumDigits(n/10);
}
public static void main(String[] args) {
[Link](sumDigits(1234)); // 10
}
}

Q3 [Medium] Reverse a string using recursion


Explanation: Take first char, call function for rest, append char at last.
class RecQ3 {
static String reverse(String s) {
if([Link]()) return s;
return reverse([Link](1)) + [Link](0);
}
public static void main(String[] args) {
[Link](reverse("java")); // avaj
}
}

Q4 [Medium-Hard] Check if a string is palindrome using recursion


Explanation: Compare first & last char, then check middle substring.
class RecQ4 {
static boolean isPalindrome(String s, int start, int end) {
if(start >= end) return true;
if([Link](start) != [Link](end)) return false;
return isPalindrome(s, start+1, end-1);
}
public static void main(String[] args) {
String s = "madam";
[Link](isPalindrome(s, 0, [Link]()-1)); // true
}
}

Q5 [Hard] Tower of Hanoi


Explanation: Move n-1 disks → move largest → move n-1 again.
class RecQ5 {
static void hanoi(int n, char from, char to, char aux) {
if(n == 1) {
[Link]("Move disk 1 from " + from + " to " + to);
return;
}
hanoi(n-1, from, aux, to);
[Link]("Move disk " + n + " from " + from + " to " + to);
hanoi(n-1, aux, to, from);
}
public static void main(String[] args) {
hanoi(3, 'A', 'C', 'B');
}
}

Strings

Q1 [Easy] Count vowels in a string


class StrQ1 {
static int countVowels(String s) {
int count=0;
s = [Link]();
for(char c : [Link]()) {
if("aeiou".indexOf(c) != -1) count++;
}
return count;
}
public static void main(String[] args) {
[Link](countVowels("Hello Java")); // 4
}
}

Q2 [Easy-Medium] Check if two strings are anagrams


import [Link];
class StrQ2 {
static boolean isAnagram(String s1, String s2) {
char[] a = [Link](" ", "").toLowerCase().toCharArray();
char[] b = [Link](" ", "").toLowerCase().toCharArray();
[Link](a); [Link](b);
return [Link](a, b);
}
public static void main(String[] args) {
[Link](isAnagram("listen", "silent")); // true
}
}

Q3 [Medium] First non-repeated character in a string


import [Link];
class StrQ3 {
static char firstUnique(String s) {
LinkedHashMap<Character,Integer> map = new LinkedHashMap<>();
for(char c : [Link]()) [Link](c, [Link](c,0)+1);
for(char c : [Link]()) if([Link](c)==1) return c;
return '_';
}
public static void main(String[] args) {
[Link](firstUnique("swiss")); // w
}
}

Q4 [Medium-Hard] Longest substring without repeating characters


import [Link].*;
class StrQ4 {
static int longestUnique(String s) {
HashSet<Character> set = new HashSet<>();
int left=0, max=0;
for(int right=0; right<[Link](); right++) {
while([Link]([Link](right)))
[Link]([Link](left++));
[Link]([Link](right));
max = [Link](max, right-left+1);
}
return max;
}
public static void main(String[] args) {
[Link](longestUnique("abcabcbb")); // 3
}
}

Q5 [Hard] Check if a string is rotation of another


class StrQ5 {
static boolean isRotation(String s1, String s2) {
if([Link]()!=[Link]()) return false;
return (s1+s1).contains(s2);
}
public static void main(String[] args) {
[Link](isRotation("waterbottle", "erbottlewat")); // true
}
}

Arrays

Q1 [Easy] Find largest element in array


class ArrQ1 {
static int largest(int[] arr) {
int max = arr[0];
for(int n : arr) if(n > max) max = n;
return max;
}
public static void main(String[] args) {
int[] arr = {2,8,5,1,10};
[Link](largest(arr)); // 10
}
}

Q2 [Easy-Medium] Reverse an array


class ArrQ2 {
static void reverse(int[] arr) {
int i=0, j=[Link]-1;
while(i<j) {
int temp = arr[i]; arr[i]=arr[j]; arr[j]=temp;
i++; j--;
}
}
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
reverse(arr);
for(int n : arr) [Link](n+" ");
}
}

Q3 [Medium] Second largest element in array


class ArrQ3 {
static int secondLargest(int[] arr) {
int first=Integer.MIN_VALUE, second=Integer.MIN_VALUE;
for(int n : arr) {
if(n > first) {
second = first;
first = n;
} else if(n > second && n!=first) {
second = n;
}
}
return second;
}
public static void main(String[] args) {
int[] arr = {10,20,4,45,99};
[Link](secondLargest(arr)); // 45
}
}

Q4 [Medium-Hard] Move all zeros to end of array


class ArrQ4 {
static void moveZeros(int[] arr) {
int index=0;
for(int n : arr) if(n!=0) arr[index++] = n;
while(index < [Link]) arr[index++] = 0;
}
public static void main(String[] args) {
int[] arr = {0,1,0,3,12};
moveZeros(arr);
for(int n : arr) [Link](n+" ");
}
}

Q5 [Hard] Find missing number in an array (1 to n)


class ArrQ5 {
static int missingNumber(int[] arr, int n) {
int total = n*(n+1)/2;
int sum=0;
for(int num : arr) sum += num;
return total - sum;
}
public static void main(String[] args) {
int[] arr = {1,2,4,5,6};
[Link](missingNumber(arr,6)); // 3
}
}

Common questions

Powered by AI

To find the longest substring without repeating characters, employ a sliding window technique. Use a hash set to track characters within the current window. Expand the window by adding characters from the end until a duplicate is encountered. At that point, incrementally contract the window from the start until the duplicate is removed. Track the maximum length encountered during this dynamic window adjustment .

The recursive process for printing numbers from 1 to N involves decrementing the number N in each recursive call and printing it after the call returns. Specifically, the base case checks if N is zero, upon which the recursion stops. Otherwise, the function calls itself with N-1 and prints the current value of N after the recursive call returns, resulting in numbers 1 up to N being printed in order .

To determine if a string is a palindrome using recursion, compare the first and last characters of the string. If they are identical, the function recursively checks the substring that excludes these characters. The base case is reached when the pointers meet or cross each other, indicating that the entire string has been verified as symmetrical. If any characters do not match, the function immediately returns false .

To compute the sum of digits of a number using recursion, you repeatedly break down the number into its last digit and the remaining number. The last digit is found using the modulus operation (n % 10), and the remaining is obtained by integer division (n / 10). The base case for this recursion is when the number becomes zero, at which point the function returns 0, terminating the recursion .

To determine if one string is a rotation of another, first check if they are of equal length. Concatenate the first string with itself and check if the second string is a substring of this concatenated result. This operation effectively accounts for all possible rotations. If the second string is found within, it confirms that the strings are rotations of each other .

The algorithm for finding the first non-repeated character in a string uses a LinkedHashMap to map each character to its frequency in the string. The LinkedHashMap preserves the order of insertion, enabling sequential scanning. Each character of the string is iterated, updating the frequency map. A second traversal checks for the first character with a frequency of one, identifying it as the first non-repeating character .

The approach to find the missing number in an array of distinct numbers from 1 to n is to compute the theoretical sum of numbers from 1 to n using the formula n*(n+1)/2. Then calculate the actual sum of the numbers present in the array. The difference between the theoretical sum and the actual sum yields the missing number. This leverages the properties of arithmetic sequences and eliminates the need for additional data structures .

The recursive solution to the Tower of Hanoi problem involves strategically moving the smallest (n-1) number of disks to an auxiliary peg, then moving the largest disk directly to the destination peg. Subsequently, the (n-1) disks that were moved to the auxiliary peg are moved to the destination peg on top of the largest disk. This recursive strategy breaks down the problem into smaller subsets until it is trivial enough to solve directly, with the base case involved when only a single disk needs to be moved .

The recursive approach to reversing a string involves decomposing the string into its first character and the remaining substring. The function calls itself with the remaining substring and appends the first character to the result of the recursive call. The base case occurs when the substring is empty, at which point it returns the empty string, allowing the characters to be concatenated in reverse order .

To verify if two strings are anagrams using Java, first remove any spaces and convert both strings to lowercase. Convert the strings into character arrays and sort them. Lastly, compare the sorted arrays; if they are identical, the original strings are anagrams. This technique effectively neutralizes any variation in character order, focusing on composition .

You might also like