[Go to site: main page, start]

0% found this document useful (0 votes)
35 views3 pages

Java Coding Challenges for Beginners

The document contains Java coding practice problems, including solutions for finding a missing number in an array, determining minimum insertions to make a string a palindrome, calculating the length of the longest consecutive subsequence, generating a character pattern based on position, and finding the maximum subarray sum with one deletion allowed. Each problem is accompanied by a code implementation and a main method for testing. These problems are designed to enhance coding skills and algorithmic thinking.

Uploaded by

bhavanipriy73
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)
35 views3 pages

Java Coding Challenges for Beginners

The document contains Java coding practice problems, including solutions for finding a missing number in an array, determining minimum insertions to make a string a palindrome, calculating the length of the longest consecutive subsequence, generating a character pattern based on position, and finding the maximum subarray sum with one deletion allowed. Each problem is accompanied by a code implementation and a main method for testing. These problems are designed to enhance coding skills and algorithmic thinking.

Uploaded by

bhavanipriy73
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

HackWithInfy Java Coding Practice Problems

1. Missing Number in Array


Find the missing number from an array of n-1 integers ranging from 1 to n.

import [Link].*;

public class MissingNumber {


public static int findMissing(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};
int n = 5;
[Link]("Missing number is: " + findMissing(arr, n));
}
}

2. Minimum Insertions to Make a String Palindrome


Find the minimum number of insertions to make a string a palindrome.

public class MinInsertPalindrome {


public static int minInsertions(String s) {
int n = [Link]();
int[][] dp = new int[n][n];

for (int gap = 1; gap < n; gap++) {


for (int l = 0, r = gap; r < n; l++, r++) {
if ([Link](l) == [Link](r)) {
dp[l][r] = dp[l+1][r-1];
} else {
dp[l][r] = [Link](dp[l+1][r], dp[l][r-1]) + 1;
}
}
}
return dp[0][n-1];
}

public static void main(String[] args) {


String s = "abcda";
[Link]("Minimum insertions: " + minInsertions(s));
}
}

3. Longest Consecutive Subsequence


Return the length of the longest sequence of consecutive elements.

import [Link].*;

public class LongestConsecutive {


public static int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) [Link](num);

int longest = 0;
for (int num : set) {
if (![Link](num - 1)) {
int currentNum = num;
int count = 1;

while ([Link](currentNum + 1)) {


currentNum++;
count++;
}

longest = [Link](longest, count);


}
}

return longest;
}

public static void main(String[] args) {


int[] nums = {100, 4, 200, 1, 3, 2};
[Link]("Longest Consecutive Sequence Length: " +
longestConsecutive(nums));
}
}

4. String Pattern Generator


Print a pattern with each character repeated based on its position.

public class PatternPrinter {


public static void main(String[] args) {
String s = "abc";
for (int i = 0; i < [Link](); i++) {
char c = [Link](i);
for (int j = 0; j <= i; j++) {
[Link](c);
}
[Link]();
}
}
}

5. Maximum Subarray Sum with One Deletion Allowed


Find the maximum sum of a subarray with at most one deletion.

public class MaxSumOneDeletion {


public static int maximumSum(int[] arr) {
int n = [Link];
int[] f = new int[n]; // max sum ending at i
int[] b = new int[n]; // max sum starting at i

f[0] = arr[0];
int maxSum = arr[0];

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


f[i] = [Link](arr[i], f[i - 1] + arr[i]);
maxSum = [Link](maxSum, f[i]);
}

b[n - 1] = arr[n - 1];


for (int i = n - 2; i >= 0; i--) {
b[i] = [Link](arr[i], b[i + 1] + arr[i]);
}

for (int i = 1; i < n - 1; i++) {


maxSum = [Link](maxSum, f[i - 1] + b[i + 1]);
}

return maxSum;
}

public static void main(String[] args) {


int[] arr = {1, -2, 0, 3};
[Link]("Maximum sum with one deletion: " + maximumSum(arr));
}
}

Common questions

Powered by AI

The algorithm uses two dynamic arrays: 'f' to store the maximum sum of subarrays ending at each index, and 'b' to store maximum subarray sums starting at each index. First, it computes forward sums to populate 'f', then backward sums for 'b'. By comparing these, the algorithm finds the maximum sum of a subarray with at most one deletion by checking sums that exclude one element between valid forward and backward subarrays .

Edge cases include scenarios such as arrays with all negative numbers, single-element arrays, or arrays where the optimal subarray involves deleting the element with the highest absolute value. The algorithm manages these through the dynamic arrays 'f' and 'b', ensuring it considers segments where retaining or removing any single element could benefit the overall maximal sum calculation .

The algorithm uses a HashSet to store unique numbers from the array, then iterates through the set checking for the start of each potential consecutive sequence (a number without a predecessor in the set). For each starting point found, it counts the length of the sequence by checking subsequent consecutive numbers. The maximum sequence length encountered is returned as the result .

Dynamic programming is beneficial in scenarios where the problem can be broken down into overlapping subproblems with optimal substructure properties. For the palindrome insertion problem, the dynamic programming approach helps efficiently resolve various substring match cases by reusing computed results for smaller substrings, reducing computational redundancy and overhead .

The pattern generation algorithm achieves this by having a nested loop where the outer loop runs over each index of the string, and the inner loop iterates up to the current index (inclusive) to print the corresponding character. This inner loop iteration ensures that each character is printed progressively more times as its position in the string increases .

The dynamic programming approach calculates the solution by building a 2D array 'dp', where dp[i][j] represents the minimum insertions needed to make the substring from index i to j a palindrome. By iterating over possible substring lengths and updating dp based on character matches or calculating minimum insertions when they differ, the algorithm efficiently determines the minimum insertions required for the entire string .

The algorithm calculates the total sum of numbers from 1 to n using the formula n * (n + 1) / 2. It then subtracts the sum of the elements present in the array from this total to find the missing number. This approach takes advantage of the properties of arithmetic series to efficiently determine the missing element without a need for sorting or additional space beyond simple counters .

The formula n * (n + 1) / 2 is used to calculate the sum of the first n natural numbers efficiently due to the arithmetic progression properties. This computed sum provides a benchmark against which the actual sum of the array elements can be compared to determine the missing number by finding the discrepancy .

Hashing enables the algorithm to achieve average O(1) lookup times for checking the existence of numbers, allowing the algorithm to quickly determine the starting point of potential sequences. This avoids the need for sorting or iterating through the array repeatedly, thus optimizing the sequence identification process .

The code uses nested loops where the outer loop iterates over each character in the string, and the inner loop is responsible for printing each character multiple times up to its position index in the string. This results in a triangular pattern where the number of repetitions increases with each step through the string .

You might also like