Challenging Java programs and succeeding in coding interviews-9

In part 9 of our series on Java programs and succeeding in coding interviews, we will solve some programs and provide a brief explanation of how each program works.

Our aim is to help beginners easily understand and learn these programs. By understanding these programs, you will be able to enhance your Java programming skills and be better prepared for coding interviews.

So, whether you are a beginner or an experienced Java developer, join us in this tutorial and take your Java programming skills to the next level.

Write a Java program that finds duplicate characters in a string

import java.util.HashMap;
import java.util.Map;

public class JavaTechypid {
    public static void main(String[] args) {
        String str = "hello world";
        Map<Character, Integer> charMap = new HashMap<Character, Integer>();
        char[] charArray = str.toCharArray();
        for (char ch : charArray) {
            if (charMap.containsKey(ch)) {
                charMap.put(ch, charMap.get(ch) + 1);
            } else {
                charMap.put(ch, 1);
            }
        }
        for (Map.Entry<Character, Integer> entry : charMap.entrySet()) {
            if (entry.getValue() > 1) {
                System.out.println("Duplicate character: " + entry.getKey() + ", Count: " + entry.getValue());
            }
        }
    }
}

Output:

Duplicate character: l, Count: 3
Duplicate character: o, Count: 2

Explanation Of Above Java Code:

It starts by creating a HashMap to store each character and its frequency in the string.

Then, it loops through each character in the string and checks if it is already present in the HashMap.

If it is, it increments its frequency value in the map. If not, it adds it to the map with a frequency of 1.

Finally, it loops through the map and prints out all characters that have a frequency greater than 1, indicating they are duplicates in the string.

For example, if the input string is “hello world”, the program will output “l” and “o” as the duplicate characters since they each occur twice in the string.

Write a program to find duplicate elements in an array in Java

public class JavaTechypid {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 2, 3, 6, 7, 8, 8};

        // iterate through each element in the array
        for (int i = 0; i < arr.length; i++) {
            // compare the current element with all the elements that come after it
            for (int j = i + 1; j < arr.length; j++) {
                // if a match is found, print the duplicate element
                if (arr[i] == arr[j]) {
                    System.out.println("Duplicate element found: " + arr[i]);
                }
            }
        }
    }
}

Output:

Duplicate element found: 2
Duplicate element found: 3
Duplicate element found: 8

Explanation Of Above Java Code:

The above code uses two nested loops to compare each element in the array with every other element.

The first loop iterates over each element in the array, and the second loop compares the current element with every other element after it in the array.

If two elements are found to be equal, the code increments a counter variable and prints the duplicate element.

The counter variable keeps track of how many duplicate elements have been found.

The code also uses a boolean variable called flag to keep track of whether any duplicates have been found. If no duplicates are found, the program prints a message indicating that there are no duplicates in the array.

Write a a Java program to find the sum of all digits of a number

import java.util.Scanner;

public class JavaTechypid {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        int sum = 0;
        while (num > 0) {
            int digit = num % 10;
            sum += digit;
            num /= 10;
        }

        System.out.println("Sum of digits: " + sum);
    }
}

Output:

Enter a number: 50
Sum of digits: 5

Enter a number: 55
Sum of digits: 10

Explanation Of Above Java Code:

The above we initialize a variable sum to 0, which will store the sum of digits of the input number.

We use a while loop to extract each digit of the number by taking the modulus of the number with 10.

This gives us the rightmost digit of the number.
We add this digit to the sum variable and then remove it from the number by dividing it by 10.

We repeat the above step until the number becomes 0, which means all digits have been extracted.

Finally, we print the sum of digits.

Write a program to check whether a given number is binary or not

import java.util.Scanner;

public class JavaTechypid {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        String num = input.nextLine();
        boolean isBinary = true;
        for (int i = 0; i < num.length(); i++) {
            char c = num.charAt(i);
            if (c != '0' && c != '1') {
                isBinary = false;
                break;
            }
        }
        if (isBinary) {
            System.out.println(num + " is a binary number.");
        } else {
            System.out.println(num + " is not a binary number.");
        }
        input.close();
    }
}

Output:

Enter a number: 10204982
10204982 is not a binary number

Enter a number: 101100
101100 is a binary number

Explanation Of Above Java Code:

We first take the input number as a string from the user.

We set a boolean flag isBinary to true initially.

We loop through each character of the input string and check if it’s either 0 or 1.

If any other character is encountered, we set the isBinary flag to false and break out of the loop.

Finally, we check the value of isBinary and print whether the input number is binary or not.

Write a program to merge two sorted arrays in Java

public class JavaTechypid {
    public static void main(String[] args) {
        int[] arr1 = {1, 3, 5, 7};
        int[] arr2 = {2, 4, 6, 8};
        int[] mergedArr = merge(arr1, arr2);
        System.out.print("Merged Array: ");
        for (int i : mergedArr) {
            System.out.print(i + " ");
        }
    }
    
    public static int[] merge(int[] arr1, int[] arr2) {
        int i = 0, j = 0, k = 0;
        int[] mergedArr = new int[arr1.length + arr2.length];
        while (i < arr1.length && j < arr2.length) {
            if (arr1[i] < arr2[j]) {
                mergedArr[k++] = arr1[i++];
            } else {
                mergedArr[k++] = arr2[j++];
            }
        }
        while (i < arr1.length) {
            mergedArr[k++] = arr1[i++];
        }
        while (j < arr2.length) {
            mergedArr[k++] = arr2[j++];
        }
        return mergedArr;
    }
}

Output:

Merged Array: 1 2 3 4 5 6 7 8

Explanation Of Above Java Code:

In this program, we first create two sorted arrays arr1 and arr2. We then call the merge() function to merge the two arrays.

The merge() function takes two parameters, arr1 and arr2, and returns a new array that contains all the elements of the two input arrays in sorted order.

We use three pointers i, j, and k to traverse the two input arrays and the merged array, respectively.

We compare the current elements of arr1 and arr2 at indices i and j, and add the smaller element to the merged array at index k.

We then increment the respective pointer and continue the process until one of the input arrays is exhausted.

Finally, we add any remaining elements in the input arrays to the merged array and return it.

Write Java program that implements a stack using a linked list

public class JavaTechypid {
    
    private static class Node {
        int data;
        Node next;
        Node(int data) {
            this.data = data;
        }
    }
    
    private Node top;
    
    public boolean isEmpty() {
        return top == null;
    }
    
    public int peek() {
        if (top == null) {
            throw new IllegalStateException("Stack is empty");
        }
        return top.data;
    }
    
    public void push(int data) {
        Node node = new Node(data);
        node.next = top;
        top = node;
    }
    
    public int pop() {
        if (top == null) {
            throw new IllegalStateException("Stack is empty");
        }
        int data = top.data;
        top = top.next;
        return data;
    }
    
    public static void main(String[] args) {
        JavaTechypid stack = new JavaTechypid();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        System.out.println(stack.pop()); // Output: 3
        System.out.println(stack.pop()); // Output: 2
        System.out.println(stack.peek()); // Output: 1
    }
}

Output:

3
2
1

Explanation Of Above Java Code:

This program defines a private Node class to represent the elements of the stack, with each node holding an integer value and a reference to the next node in the stack.

The class provides methods for checking if the stack is empty (isEmpty()), peeking at the top element without removing it (peek()), pushing a new element onto the stack (push()), and popping the top element off the stack (pop()).

In the push() method, a new node is created and inserted at the top of the stack by setting its next field to the current top node and updating the top field to the new node.

In the pop() method, the top node is removed by updating the top field to reference the next node in the stack and returning the data value of the former top node.

Write a java program to sort a stack using another stack

import java.util.Stack;

public class JavaTechypid {
    public static void sortStack(Stack<Integer> stack) {
        Stack<Integer> tempStack = new Stack<>();

        while (!stack.isEmpty()) {
            int temp = stack.pop();

            while (!tempStack.isEmpty() && tempStack.peek() > temp) {
                stack.push(tempStack.pop());
            }

            tempStack.push(temp);
        }

        while (!tempStack.isEmpty()) {
            stack.push(tempStack.pop());
        }
    }

    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(34);
        stack.push(3);
        stack.push(31);
        stack.push(98);
        stack.push(92);
        stack.push(23);

        System.out.println("Original Stack: " + stack);
        sortStack(stack);
        System.out.println("Sorted Stack: " + stack);
    }
}

Output:

Original Stack: [34, 3, 31, 98, 92, 23]
Sorted Stack: [98, 92, 34, 31, 23, 3]

Explanation Of Above Java Code:

We create a temporary stack to hold the elements during the sorting process.

Pop the top element from the original stack and store it in a variable.

While the temporary stack is not empty and the top element is greater than the popped element, pop the top element from the temporary stack and push it back onto the original stack.

Push the popped element onto the temporary stack.

Repeat steps 2-4 until the original stack is empty.

Now the temporary stack contains the elements in sorted order. Pop the elements from the temporary stack and push them back onto the original stack to get the elements in descending order.

Write a Java program that reverses a singly linked list

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

class JavaTechypid {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;

        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }

        return prev;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        JavaTechypid obj = new JavaTechypid();
        ListNode reversed = obj.reverseList(head);

        while (reversed != null) {
            System.out.print(reversed.val + " ");
            reversed = reversed.next;
        }
    }
}

Output:

5 4 3 2 1

Explanation Of Above Java Code:

In the reverseList method, we maintain two pointers prev and curr.

We traverse the list by updating curr to its next node and set its next to the previous node prev.

Finally, we update prev and curr to move to the next node.

When we reach the end of the list, prev points to the new head of the reversed list.

Leave a Reply