0% found this document useful (0 votes)
2 views6 pages

Java DSA Practice

The document provides a comprehensive guide on Java Data Structures and Algorithms (DSA) focusing on logic building, covering conditionals, loops, strings, and arrays. Each section includes specific problems with example inputs, outputs, and efficient code solutions, along with time and space complexity analysis. The content is aimed at enhancing understanding and practical skills in programming through various algorithmic challenges.

Uploaded by

aneja1145
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)
2 views6 pages

Java DSA Practice

The document provides a comprehensive guide on Java Data Structures and Algorithms (DSA) focusing on logic building, covering conditionals, loops, strings, and arrays. Each section includes specific problems with example inputs, outputs, and efficient code solutions, along with time and space complexity analysis. The content is aimed at enhancing understanding and practical skills in programming through various algorithmic challenges.

Uploaded by

aneja1145
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 DSA Practice

Logic Building — Fundamentals to Arrays


Pathan Sabiya | [Link] CSE-AI | Chalapathi Institute of Technology

SECTION 1 — Conditionals
Q1. Positive, Negative, or Zero
Input: -5 Output: Negative
public static String checkNum(int n) {
if (n > 0) return "Positive";
else if (n < 0) return "Negative";
return "Zero";
}

Time: O(1) | Space: O(1)

Q2. Even or Odd


Input: 7 Output: Odd
public static String checkEvenOdd(int n) {
if (n % 2 == 0) return "Even";
return "Odd";
}

Time: O(1) | Space: O(1)

Q3. Divisible by 5
Input: 25 Output: Divisible by 5
public static String checkDivisible(int n) {
if (n % 5 == 0) return "Divisible by 5";
return "Not divisible by 5";
}

Time: O(1) | Works for negative numbers too

Q4. Leap Year Check


Input: 2024 Output: Leap Year
public static String checkLeapYear(int n) {
if ((n % 4 == 0 && n % 100 != 0) || (n % 400 == 0))
return "Leap Year";
return "Not a Leap Year";
}

Time: O(1) | Tricky: 1900 is NOT leap, 2000 IS leap

Q5. Valid Triangle (3 sides)


Input: 3 4 5 Output: Valid Triangle
public static String checkValidTriangle(int a, int b, int c) {
if (a+b > c && b+c > a && c+a > b)
return "Valid Triangle";
return "Not a Valid Triangle";
}

Triangle Inequality Theorem: sum of any two sides > third side

Q6. Grade Calculator


Input: 85 Output: B
public static String checkGrade(int n) {
if (n >= 90 && n <= 100) return "A";
else if (n >= 80) return "B";
else if (n >= 70) return "C";
else if (n >= 60) return "D";
return "F";
}

Time: O(1) | Always check highest range first

Q7. FizzBuzz
Input: 15 Output: FizzBuzz | Input: 9 Output: Fizz
public static String fizzBuzz(int n) {
if (n % 3 == 0 && n % 5 == 0) return "FizzBuzz";
else if (n % 3 == 0) return "Fizz";
else if (n % 5 == 0) return "Buzz";
return "" + n;
}

Check BOTH condition first — order matters!

SECTION 2 — Loops & Number Logic


Q8. Count Digits in a Number
Input: 12345 Output: 5
public static int countDigits(int n) {
if (n == 0) return 1;
int count = 0;
while (n > 0) { n /= 10; count++; }
return count;
}

Pattern: while(n>0) { n/=10; count++; } — reusable template!

Q9. Reverse a Number


Input: 1234 Output: 4321 | Input: 120 Output: 21
public static int reverseNum(int n) {
int rev = 0;
while (n != 0) {
int digit = n % 10;
rev = rev * 10 + digit;
n /= 10;
}
return rev;
}

Key formula: rev = rev*10 + digit

Q10. Sum of Digits


Input: 1234 Output: 10
public static int sumOfDigits(int n) {
int sum = 0;
while (n > 0) { sum += n % 10; n /= 10; }
return sum;
}

n=0 returns sum=0 automatically — no special case needed

Q11. Check Prime (Optimized)


Input: 7 Output: Prime | Input: 1 Output: Not Prime
public static String checkPrime(int n) {
if (n <= 1) return "Not Prime";
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return "Not Prime";
}
return "Prime";
}

O(sqrt(n)) — check only up to sqrt(n), not n!

Q12. Factorial of a Number


Input: 5 Output: 120 | Input: 0 Output: 1
public static int factorial(int n) {
int fact = 1;
for (int i = 2; i <= n; i++) fact *= i;
return fact;
}

Start fact=1, not 0 — multiplying by 0 gives 0 always!

Q13. Armstrong Number


Input: 153 Output: Armstrong
public static void checkArmstrong(int num) {
int original = num, sum = 0;
while (num > 0) {
int d = num % 10;
sum += d * d * d;
num /= 10;
}
[Link](sum == original ? "Armstrong" : "Not Armstrong");
}

153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

Q14. Fibonacci Series


Input: 7 Output: 0 1 1 2 3 5 8
public static void fibonacci(int n) {
int first = 0, second = 1;
[Link](first + " " + second);
for (int i = 2; i < n; i++) {
int next = first + second;
[Link](" " + next);
first = second;
second = next;
}
}

Print first two outside loop, then n-2 more inside loop

Q15. GCD — Euclid's Algorithm


Input: 12 8 Output: 4
public static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}

Most efficient GCD algorithm — O(log(min(a,b)))

SECTION 3 — Strings
Q16. Reverse a String
Input: "hello" Output: "olleh"
public static void reverseStr(String str) {
StringBuilder rev = new StringBuilder();
for (int i = [Link]()-1; i >= 0; i--)
[Link]([Link](i));
[Link]([Link]());
}

Use StringBuilder (not String +=) — avoids O(n^2) concatenation

Q17. Palindrome Check (Two Pointer)


Input: "racecar" Output: true
public static boolean checkPalindrome(String str) {
int left = 0, right = [Link]() - 1;
while (left < right) {
if ([Link](left) != [Link](right)) return false;
left++; right--;
}
return true;
}

Two pointer: compare from both ends, early exit on mismatch

Q18. Count Vowels and Consonants


Input: "hello world" Output: Vowels: 3, Consonants: 7
public static void checkVowCon(String str) {
int vow = 0, con = 0;
char[] ch = [Link]().toCharArray();
for (char c : ch) {
if (c == ' ') continue;
if ("aeiou".indexOf(c) != -1) vow++;
else con++;
}
[Link]("Vowels: " + vow + " Consonants: " + con);
}

Use "aeiou".indexOf(c) != -1 — cleaner than 5 || conditions

Q19. Anagram Check


Input: "listen", "silent" Output: true
public static boolean checkAnagram(String s1, String s2) {
char[] ch1 = [Link]().toCharArray();
char[] ch2 = [Link]().toCharArray();
[Link](ch1);
[Link](ch2);
return [Link](ch1, ch2);
}

[Link]() for arrays, not .equals() — reference vs value!

Q20. First Non-Repeating Character


Input: "swiss" Output: w
public static void firstNonRepeating(String str) {
for (int i = 0; i < [Link](); i++) {
char c = [Link](i);
if ([Link](c) == [Link](c)) {
[Link](c); return;
}
}
[Link]("No unique character");
}

indexOf == lastIndexOf means character appears only once

SECTION 4 — Arrays
Q21. Find Maximum Element
Input: [3,7,2,9,4,1] Output: 9
public static int findMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < [Link]; i++)
if (arr[i] > max) max = arr[i];
return max;
}

Time: O(n) | Space: O(1) — optimal, cannot do better

Q22. Find Second Largest


Input: [12,35,1,10,34,1] Output: 34
public static int secondMax(int[] arr) {
int max = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int x : arr) {
if (x > max) { second = max; max = x; }
else if (x > second && x != max) second = x;
}
return second;
}

Single pass O(n) — check both conditions in one loop

Q23. Reverse Array (In-Place)


Input: [1,2,3,4,5] Output: [5,4,3,2,1]
public static void reverseArr(int[] arr) {
int left = 0, right = [Link] - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++; right--;
}
}

Two pointer swap — O(n/2) = O(n), O(1) space

Q24. Array Palindrome Check


Input: [1,2,3,2,1] Output: true
public static boolean checkPalindrome(int[] arr) {
int left = 0, right = [Link] - 1;
while (left < right) {
if (arr[left] != arr[right]) return false;
left++; right--;
}
return true;
}

Same two pointer logic as String palindrome

Q25. Rotate Array Left by One


Input: [1,2,3,4,5] Output: [2,3,4,5,1]
public static void rotateLeft(int[] arr) {
int temp = arr[0];
for (int i = 0; i < [Link] - 1; i++)
arr[i] = arr[i + 1];
arr[[Link] - 1] = temp;
}

Save first element, shift all left, place saved at end

Q26. Move Zeros to End (Two Pointer)


Input: [0,1,0,3,12] Output: [1,3,12,0,0]
public static void moveZeros(int[] arr) {
int j = 0;
for (int i = 0; i < [Link]; i++) {
if (arr[i] == 0) continue;
arr[j] = arr[i]; j++;
}
for (int i = j; i < [Link]; i++) arr[i] = 0;
[Link]([Link](arr));
}

j = slow pointer (next non-zero slot) | i = fast scanner

Q27. Contains Duplicate


Input: [1,2,3,1] Output: true
public static boolean hasDuplicate(int[] arr) {
[Link](arr);
for (int i = 0; i < [Link] - 1; i++)
if (arr[i] == arr[i+1]) return true;
return false;
}

Sort first — duplicates become adjacent! O(n log n)

LinkedIn: [Link]/in/pathan-sabiya | GitHub: [Link]/sabiyams | Portfolio: [Link]/personal_portfolio-/

You might also like