- Get link
- X
- Other Apps
To enjoy the success of our 25% completion of our journey, here are 25 Must Know Basic Problems for all Coding Enthusiasts! Enjoy your gift!!
1. Reverse an Array
Description: Reverse the order of elements in an array.
Sample Input: [1, 2, 3, 4]
Sample Output: [4, 3, 2, 1]
Python
def reverse_array(arr):
return arr[::-1]
arr = [1, 2, 3, 4]
print(reverse_array(arr))
Java
import java.util.*;
public class ReverseArray {
public static int[] reverseArray(int[] arr) {
int left = 0, right = arr.length - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
return arr;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
System.out.println(Arrays.toString(reverseArray(arr)));
}
}
2. Find the Maximum and Minimum Element in an Array
Description: Find the maximum and minimum elements in a given array.
Sample Input: [4, 5, 1, 9, 2]
Sample Output: Max: 9 Min: 1
Python
def find_max_min(arr):
return max(arr), min(arr)
arr = [4, 5, 1, 9, 2]
print("Max:", find_max_min(arr)[0], "Min:", find_max_min(arr)[1])
Java
import java.util.*;
public class MaxMin {
public static void findMaxMin(int[] arr) {
int max = Arrays.stream(arr).max().getAsInt();
int min = Arrays.stream(arr).min().getAsInt();
System.out.println("Max: " + max + " Min: " + min);
}
public static void main(String[] args) {
int[] arr = {4, 5, 1, 9, 2};
findMaxMin(arr);
}
}
3. Check if a String is a Palindrome
Description: Check if a string reads the same forward and backward.
Sample Input: "racecar"
Sample Output: True
Python
def is_palindrome(s):
return s == s[::-1]
s = "racecar"
print(is_palindrome(s))
Java
public class Palindrome {
public static boolean isPalindrome(String s) {
String reversed = new StringBuilder(s).reverse().toString();
return s.equals(reversed);
}
public static void main(String[] args) {
String s = "racecar";
System.out.println(isPalindrome(s));
}
}
4. Find the Largest Prime Factor of a Number
Description: Find the largest prime factor of a given number.
Sample Input: 56
Sample Output: 7
Python
def largest_prime_factor(n):
factor = 2
while factor * factor <= n:
if n % factor == 0:
n //= factor
else:
factor += 1
return n
n = 56
print(largest_prime_factor(n))
Java
public class LargestPrimeFactor {
public static int largestPrimeFactor(int n) {
int factor = 2;
while (factor * factor <= n) {
if (n % factor == 0) {
n /= factor;
} else {
factor++;
}
}
return n;
}
public static void main(String[] args) {
int n = 56;
System.out.println(largestPrimeFactor(n));
}
}
5. Check if Two Strings are Anagrams
Sample Input:
"listen", "silent"
Sample Output:
True
Python
def are_anagrams(s1, s2):
return sorted(s1) == sorted(s2)
s1, s2 = "listen", "silent"
print(are_anagrams(s1, s2))
Java
import java.util.Arrays;
public class Anagram {
public static boolean areAnagrams(String s1, String s2) {
char[] arr1 = s1.toCharArray();
char[] arr2 = s2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}
public static void main(String[] args) {
String s1 = "listen";
String s2 = "silent";
System.out.println(areAnagrams(s1, s2));
}
}
6. Count Occurrences of a Characted in a String
Sample Input:
"hello", 'l'
Sample Output:
2
Python
def count_occurrences(s, char):
return s.count(char)
s = "hello"
char = 'l'
print(count_occurrences(s, char))
Java
public class CountOccurrences {
public static int countOccurrences(String s, char c) {
int count = 0;
for (char ch : s.toCharArray()) {
if (ch == c) count++;
}
return count;
}
public static void main(String[] args) {
String s = "hello";
char c = 'l';
System.out.println(countOccurrences(s, c));
}
}
7. Find the Missing Number in an Array
Sample Input:
[1, 2, 3, 5]
Sample Output:
4
Python
def find_missing_number(arr):
n = len(arr) + 1
total_sum = n * (n + 1) // 2
return total_sum - sum(arr)
arr = [1, 2, 3, 5]
print(find_missing_number(arr))
Java
public class MissingNumber {
public static int findMissingNumber(int[] arr) {
int n = arr.length + 1;
int totalSum = n * (n + 1) / 2;
int arraySum = 0;
for (int num : arr) {
arraySum += num;
}
return totalSum - arraySum;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 5};
System.out.println(findMissingNumber(arr));
}
}
8. Move All Zeros to the End of an Array
Sample Input:
[0, 1, 0, 3, 12]
Sample Output:
[1, 3, 12, 0, 0]
Python
def move_zeros(arr):
count = arr.count(0)
arr = [x for x in arr if x != 0]
return arr + [0] * count
arr = [0, 1, 0, 3, 12]
print(move_zeros(arr))
Java
public class MoveZeros {
public static int[] moveZeros(int[] arr) {
int[] result = new int[arr.length];
int index = 0;
for (int num : arr) {
if (num != 0) result[index++] = num;
}
return result;
}
public static void main(String[] args) {
int[] arr = {0, 1, 0, 3, 12};
System.out.println(Arrays.toString(moveZeros(arr)));
}
}
9. Check if a Number is Prime
Sample Input:
7
Sample Output:
True
Python
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
n = 7
print(is_prime(n))
Java
public class Prime {
public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
public static void main(String[] args) {
int n = 7;
System.out.println(isPrime(n));
}
}
10. Find the Fibonacci Sequence Using Recursion
Sample Input:
5
Sample Output:
5
Python
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
n = 5
print(fibonacci(n))
Java
public class Fibonacci {
public static int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
public static void main(String[] args) {
int n = 5;
System.out.println(fibonacci(n));
}
}
11. Find the Factorial of a Number Using Recursion
Sample Input:
5
Sample Output:
120
Python
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
n = 5
print(factorial(n))
Java
public class Factorial {
public static int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
public static void main(String[] args) {
int n = 5;
System.out.println(factorial(n));
}
}
12. Check if a String is a Substring of Another String
Sample Input:
"hello", "ell"
Sample Output:
True
Python
def is_substring(s1, s2):
return s2 in s1
s1 = "hello"
s2 = "ell"
print(is_substring(s1, s2))
Java
public class Substring {
public static boolean isSubstring(String s1, String s2) {
return s1.contains(s2);
}
public static void main(String[] args) {
String s1 = "hello";
String s2 = "ell";
System.out.println(isSubstring(s1, s2));
}
}
13. Find the Length of a String Without Using Built-in Functions
Sample Input:
"hello"
Sample Output:
5
Python
def string_length(s):
length = 0
for char in s:
length += 1
return length
s = "hello"
print(string_length(s))
Java
public class StringLength {
public static int stringLength(String s) {
int length = 0;
for (char ch : s.toCharArray()) {
length++;
}
return length;
}
public static void main(String[] args) {
String s = "hello";
System.out.println(stringLength(s));
}
}
14. Find the Largest Element in a Matrix
Sample Input:
[[1, 2], [3, 4]]
Sample Output:
4
Python
def largest_in_matrix(matrix):
return max(max(row) for row in matrix)
matrix = [[1, 2], [3, 4]]
print(largest_in_matrix(matrix))
Java
public class LargestInMatrix {
public static int largestInMatrix(int[][] matrix) {
int max = Integer.MIN_VALUE;
for (int[] row : matrix) {
for (int num : row) {
max = Math.max(max, num);
}
}
return max;
}
public static void main(String[] args) {
int[][] matrix = {{1, 2}, {3, 4}};
System.out.println(largestInMatrix(matrix));
}
}
15. Find the Second Largest Element in an Array
Sample Input:
[4, 5, 1, 9, 2]
Sample Output:
5
Python
def second_largest(arr):
arr = list(set(arr))
arr.sort()
return arr[-2] if len(arr) > 1 else None
arr = [4, 5, 1, 9, 2]
print(second_largest(arr))
Java
import java.util.*;
public class SecondLargest {
public static int secondLargest(int[] arr) {
Set<Integer> set = new HashSet<>();
for (int num : arr) set.add(num);
List<Integer> list = new ArrayList<>(set);
Collections.sort(list);
return list.size() > 1 ? list.get(list.size() - 2) : -1;
}
public static void main(String[] args) {
int[] arr = {4, 5, 1, 9, 2};
System.out.println(secondLargest(arr));
}
}
16. Find the First Non-Repeating Character in a String
Sample Input:
"swiss"
Sample Output:
"w"
Python
def first_non_repeating(s):
for char in s:
if s.count(char) == 1:
return char
return None
s = "swiss"
print(first_non_repeating(s))
Java
public class FirstNonRepeating {
public static char firstNonRepeating(String s) {
for (char ch : s.toCharArray()) {
if (s.indexOf(ch) == s.lastIndexOf(ch)) {
return ch;
}
}
return '\0';
}
public static void main(String[] args) {
String s = "swiss";
System.out.println(firstNonRepeating(s));
}
}
17. Count the Number of Vowels in a String
Sample Input:
"hello"
Sample Output:
2
Python
def count_vowels(s):
vowels = "aeiou"
return sum(1 for char in s if char in vowels)
s = "hello"
print(count_vowels(s))
Java
public class CountVowels {
public static int countVowels(String s) {
String vowels = "aeiou";
int count = 0;
for (char ch : s.toCharArray()) {
if (vowels.indexOf(ch) != -1) count++;
}
return count;
}
public static void main(String[] args) {
String s = "hello";
System.out.println(countVowels(s));
}
}
18. Sum of Digits of a Number
Sample Input:
1234
Sample Output:
10
Python
def sum_of_digits(n):
return sum(int(digit) for digit in str(n))
n = 1234
print(sum_of_digits(n))
Java
public class SumOfDigits {
public static int sumOfDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
public static void main(String[] args) {
int n = 1234;
System.out.println(sumOfDigits(n));
}
}
19. Find the Majority Element in an Array
n/2
times in the array.Sample Input:
[3, 3, 4, 2, 4, 4, 2, 4, 4]
Sample Output:
4
Python
def majority_element(arr):
count = {}
for num in arr:
count[num] = count.get(num, 0) + 1
for num, c in count.items():
if c > len(arr) // 2:
return num
return None
arr = [3, 3, 4, 2, 4, 4, 2, 4, 4]
print(majority_element(arr))
Java
import java.util.*;
public class MajorityElement {
public static int majorityElement(int[] arr) {
Map<Integer, Integer> countMap = new HashMap<>();
for (int num : arr) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
if (entry.getValue() > arr.length / 2) {
return entry.getKey();
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {3, 3, 4, 2, 4, 4, 2, 4, 4};
System.out.println(majorityElement(arr));
}
}
20. Find the GCD of Two Numbers
Sample Input:
12, 15
Sample Output:
3
Python
def gcd(a, b):
while b:
a, b = b, a % b
return a
print(gcd(12, 15))
Java
public class GCD {
public static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static void main(String[] args) {
System.out.println(gcd(12, 15));
}
}
21. Count the Number of 1s in Binary Representation
1
s in the binary representation of a number.Sample Input:
5
(binary: 101
)Sample Output:
2
Python
def count_ones(n):
return bin(n).count('1')
print(count_ones(5))
Java
public class CountOnes {
public static int countOnes(int n) {
return Integer.bitCount(n);
}
public static void main(String[] args) {
System.out.println(countOnes(5));
}
}
22. Find the Missing Character to Form a Pangram
Sample Input:
"the quick brown fox jumps over a lazy dog"
Sample Output:
"Missing Characters: None"
Python
def missing_pangram_chars(s):
alphabet = set("abcdefghijklmnopqrstuvwxyz")
return "".join(sorted(alphabet - set(s.lower())))
s = "the quick brown fox jumps over a lazy dog"
result = missing_pangram_chars(s)
print(f"Missing Characters: {result if result else 'None'}")
Java
import java.util.*;
public class Pangram {
public static String missingPangramChars(String s) {
Set<Character> alphabet = new HashSet<>();
for (char c = 'a'; c <= 'z'; c++) alphabet.add(c);
for (char c : s.toLowerCase().toCharArray()) {
alphabet.remove(c);
}
return alphabet.isEmpty() ? "None" : alphabet.toString();
}
public static void main(String[] args) {
String s = "the quick brown fox jumps over a lazy dog";
System.out.println("Missing Characters: " + missingPangramChars(s));
}
}
23. Reverse the Words in a String
Python
def reverse_words(s):
return ' '.join(s.split()[::-1])
print(reverse_words("Hello World"))
Java
public class ReverseWords {
public static String reverseWords(String s) {
String[] words = s.split(" ");
StringBuilder result = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
result.append(words[i]);
if (i != 0) result.append(" ");
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(reverseWords("Hello World"));
}
}
24. Find the First Unique Character in a String
Python
def first_unique_char(s):
char_count = {}
for char in s:
char_count[char] = char_count.get(char, 0) + 1
for char in s:
if char_count[char] == 1:
return char
return -1
print(first_unique_char("apple"))
Java
import java.util.*;
public class FirstUniqueChar {
public static char firstUniqueChar(String s) {
Map<Character, Integer> charCount = new HashMap<>();
for (char c : s.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
for (char c : s.toCharArray()) {
if (charCount.get(c) == 1) return c;
}
return '-';
}
public static void main(String[] args) {
System.out.println(firstUniqueChar("apple"));
}
}
25. Count the Frequency of Elements in an Array
Python
def count_frequency(arr):
frequency = {}
for num in arr:
frequency[num] = frequency.get(num, 0) + 1
return frequency
print(count_frequency([1, 2, 2, 3, 3, 3]))
Java
Happy 25th to my Amazing akka!🙌🎉🐇🦋
ReplyDeleteThank you thambi!! 💛
Delete