Crack Interview: Top 10 Critical Coding Interview Questions Every Student Must Know!

Top 10 Critical Coding Interview Questions


In coding interviews, it’s important to be well-prepared for the challenges that lie ahead. Here are the top 10 critical coding interview questions you should k interviews!

To strengthen your computer science and programming skills, you can focus on the following topics:

  1. Fibonacci Sequence: You can study recursion, dynamic programming, and memoization to optimize the generation of Fibonacci sequences. Additionally, exploring the mathematical properties of the Fibonacci sequence can be beneficial.
  1. Palindrome Checker: Learning about string manipulation, character comparison, and efficient palindrome checking algorithms will be useful. If you want to handle spaces and punctuation, you can dive into topics related to regular expressions.
  2. Prime Number Generator: Exploring prime number algorithms like the Sieve of Eratosthenes and prime number testing methods such as the Miller-Rabin primality test can expand your knowledge. Additionally, studying number theory will provide a deeper understanding of prime numbers.
  3. Factorial Calculator: Understanding recursion, iterative algorithms, and the rapid growth of factorials is essential in this topic. It can also serve as a gateway to comprehend big O notation and algorithmic complexity.
  4. Sorting Algorithms: Delving into sorting algorithms and analyzing their time and space complexity will be valuable. Learning about various sorting algorithms like merge sort, heap sort, and radix sort, and exploring their real-world applications will enhance your skills.
  5. Linked List: Studying data structures and algorithms related to linked lists, such as singly linked lists, doubly linked lists, and circular linked lists, will broaden your understanding. Concepts like node insertion, deletion, and traversal are essential in this area.
  6. Binary Search Tree: Exploring binary trees, binary search trees, and balanced binary search trees like AVL and Red-Black trees is crucial. Understanding tree traversal algorithms like in-order, pre-order, and post-order traversal will add to your knowledge.
  7. String Manipulation: Learning various string manipulation techniques and algorithms, including substring search algorithms like the Knuth-Morris-Pratt algorithm and string reversal algorithms, is valuable. Understanding the importance of string immutability is also essential.
  8. Graph Traversal: Deepening your understanding of graph theory, graph representation, and common graph traversal algorithms like depth-first search (DFS) and breadth-first search (BFS) is recommended. You can apply these algorithms to solve problems such as finding the shortest path using Dijkstra’s or A* algorithms.
  9. Recursion Practice: Exploring recursion, tail recursion, and recursive problem-solving techniques is beneficial. You can study classic problems that can be solved recursively, such as the Tower of Hanoi puzzle and generating permutations and combinations.

These topics will provide you with a solid foundation in computer science and programming. They can serve as a roadmap for further learning and exploration in each area.

Solution For Each Question :Top 10 Critical Coding

1. Fibonacci Sequence:


public class Fibonacci {
    public static void main(String[] args) {
        int n = 10; // Change 'n' to generate the first 'n' Fibonacci numbers
        long[] fibonacci = new long[n];
        
        fibonacci[0] = 0;
        fibonacci[1] = 1;
        
        for (int i = 2; i < n; i++) {
            fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
        }
        
        System.out.println("Fibonacci Sequence:");
        for (long num : fibonacci) {
            System.out.print(num + " ");
        }
    }
}


2. Palindrome Checker:


public class PalindromeChecker {
   public static void main(String[] args) {
       String input = "racecar"; // Change 'input' to test different strings
       
       boolean isPalindrome = true;
       input = input.toLowerCase().replaceAll("[^a-zA-Z0-9]", ""); // Ignore case and non-alphanumeric characters
       
       int left = 0;
       int right = input.length() - 1;
       
       while (left < right) {
           if (input.charAt(left) != input.charAt(right)) {
               isPalindrome = false;
               break;
           }
           left++;
           right--;
       }
       
       if (isPalindrome) {
           System.out.println("It's a palindrome!");
       } else {
           System.out.println("It's not a palindrome.");
       }
   }
}

3. Prime Number Generator:


public class PrimeNumberGenerator {
   public static void main(String[] args) {
       int n = 50; // Change 'n' to generate prime numbers up to 'n'
       
       for (int num = 2; num <= n; num++) {
           boolean isPrime = true;
           
           for (int i = 2; i <= Math.sqrt(num); i++) {
               if (num % i == 0) {
                   isPrime = false;
                   break;
               }
           }
           
           if (isPrime) {
               System.out.print(num + " ");
           }
       }
   }
}

4 .Factorial Calculator:

public class FactorialCalculator {
    public static void main(String[] args) {
        int n = 5; // Change 'n' to calculate the factorial of a different number
        long factorial = 1;
        
        for (int i = 1; i <= n; i++) {
            factorial *= i;
        }
        
        System.out.println("Factorial of " + n + " is: " + factorial);
    }
}

5 Merge Sort:

  • Merge Sort is a divide-and-conquer algorithm that divides the input array into two halves, recursively sorts them, and then merges the sorted halves.
  • Time Complexity: O(n log n)
  • Space Complexity: O(n)
import java.util.Arrays;

public class MergeSort {
    public static void mergeSort(int[] arr) {
        if (arr.length > 1) {
            int mid = arr.length / 2;
            int[] left = Arrays.copyOfRange(arr, 0, mid);
            int[] right = Arrays.copyOfRange(arr, mid, arr.length);

            mergeSort(left);
            mergeSort(right);

            int i = 0, j = 0, k = 0;
            while (i < left.length && j < right.length) {
                if (left[i] < right[j]) {
                    arr[k++] = left[i++];
                } else {
                    arr[k++] = right[j++];
                }
            }

            while (i < left.length) {
                arr[k++] = left[i++];
            }

            while (j < right.length) {
                arr[k++] = right[j++];
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {12, 11, 13, 5, 6, 7};
        System.out.println("Original array: " + Arrays.toString(arr));
        mergeSort(arr);
        System.out.println("Sorted array: " + Arrays.toString(arr));
    }
}

Also Check other Sorting Algo :https://updategadh.com/java-project/sorting-algorithms/

See also  Java interview question - Quiz 4

6 Linked List

Let’s explore these concepts in more detail:

  1. Singly Linked List:
  • In a singly linked list, each node points to the next node in the list, forming a unidirectional chain.
  • The last node typically points to null to indicate the end of the list.
  • Common operations:
    • Insertion: To add a new node, you update the next pointer of the previous node to point to the new node.
    • Deletion: To remove a node, you update the next pointer of the previous node to skip the node to be deleted.
  1. Doubly Linked List:
  • In a doubly linked list, each node has pointers to both the next and the previous nodes, allowing bidirectional traversal.
  • It’s useful for operations that require both forward and backward traversal. doubly-linked-list Crack Interview: Top 10 Critical Coding Interview Questions Every Student Must Know!
  • Common operations:
    • Insertion: To add a new node, you update the next and previous pointers of neighboring nodes.
    • Deletion: To remove a node, you update the next and previous pointers of neighboring nodes to bypass the node to be deleted.
  1. Circular Linked List:
  • In a circular linked list, the last node’s next pointer points back to the first node, forming a closed loop.
  • It’s often used in applications where you need to traverse a list indefinitely. circular-linked-list Crack Interview: Top 10 Critical Coding Interview Questions Every Student Must Know!
  • Common operations are similar to those in singly or doubly linked lists.

Here’s an example of how to traverse a singly linked list in Python:

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
        else:
            current = self.head
            while current.next:
                current = current.next
            current.next = new_node

    def display(self):
        current = self.head
        while current:
            print(current.data, end=" -> ")
            current = current.next
        print("None")

# Example usage:
llist = LinkedList()
llist.append(1)
llist.append(2)
llist.append(3)
llist.display()

Also Check other Link List : https://updategadh.com/java-project/linked-lists-data-structures/

See also  Technical Interview Tips for freshers

Top 10 Critical Coding

7 Binary Search Tree

implementation with functions for insertion, deletion, and searching for nodes within the tree:

class TreeNode {
    int key;
    TreeNode left, right;

    public TreeNode(int item) {
        key = item;
        left = right = null;
    }
}

public class BinarySearchTree {
    TreeNode root;

    BinarySearchTree() {
        root = null;
    }

    // Insert a new key into the BST
    void insert(int key) {
        root = insertRec(root, key);
    }

    TreeNode insertRec(TreeNode root, int key) {
        if (root == null) {
            root = new TreeNode(key);
            return root;
        }

        if (key < root.key) {
            root.left = insertRec(root.left, key);
        } else if (key > root.key) {
            root.right = insertRec(root.right, key);
        }

        return root;
    }

    // Delete a key from the BST
    void delete(int key) {
        root = deleteRec(root, key);
    }

    TreeNode deleteRec(TreeNode root, int key) {
        if (root == null) {
            return root;
        }

        if (key < root.key) {
            root.left = deleteRec(root.left, key);
        } else if (key > root.key) {
            root.right = deleteRec(root.right, key);
        } else {
            // Node with only one child or no child
            if (root.left == null) {
                return root.right;
            } else if (root.right == null) {
                return root.left;
            }

            // Node with two children, get the inorder successor
            root.key = minValue(root.right);

            // Delete the inorder successor
            root.right = deleteRec(root.right, root.key);
        }

        return root;
    }

    int minValue(TreeNode root) {
        int minValue = root.key;
        while (root.left != null) {
            minValue = root.left.key;
            root = root.left;
        }
        return minValue;
    }

    // Search for a key in the BST
    boolean search(int key) {
        return searchRec(root, key);
    }

    boolean searchRec(TreeNode root, int key) {
        if (root == null) {
            return false;
        }

        if (key == root.key) {
            return true;
        }

        if (key < root.key) {
            return searchRec(root.left, key);
        }

        return searchRec(root.right, key);
    }

    // Driver method to test the BST operations
    public static void main(String[] args) {
        BinarySearchTree tree = new BinarySearchTree();

        // Insert some nodes
        tree.insert(50);
        tree.insert(30);
        tree.insert(20);
        tree.insert(40);
        tree.insert(70);
        tree.insert(60);
        tree.insert(80);

        // Search for a key
        int searchKey = 60;
        if (tree.search(searchKey)) {
            System.out.println(searchKey + " found in the BST.");
        } else {
            System.out.println(searchKey + " not found in the BST.");
        }

        // Delete a node
        int deleteKey = 30;
        tree.delete(deleteKey);
        System.out.println("After deleting " + deleteKey + ":");
        tree.inorder();
    }

    // Inorder traversal of the BST (prints the elements in sorted order)
    void inorder() {
        inorderRec(root);
    }

    void inorderRec(TreeNode root) {
        if (root != null) {
            inorderRec(root.left);
            System.out.print(root.key + " ");
            inorderRec(root.right);
        }
    }
}

8 string manipulation:

public class StringManipulation {
    public static void main(String[] args) {
        String originalString = "Hello, World!";

        // Reversing a string
        String reversedString = reverseString(originalString);
        System.out.println("Original string: " + originalString);
        System.out.println("Reversed string: " + reversedString);

        // Finding substrings
        String searchSubstring = "World";
        boolean containsSubstring = containsSubstring(originalString, searchSubstring);
        System.out.println("Does the original string contain '" + searchSubstring + "': " + containsSubstring);

        // Counting characters
        char characterToCount = 'l';
        int characterCount = countCharacters(originalString, characterToCount);
        System.out.println("Count of '" + characterToCount + "' in the original string: " + characterCount);
    }

    // Reverses a string
    public static String reverseString(String str) {
        StringBuilder reversed = new StringBuilder();
        for (int i = str.length() - 1; i >= 0; i--) {
            reversed.append(str.charAt(i));
        }
        return reversed.toString();
    }

    // Checks if a string contains a substring
    public static boolean containsSubstring(String str, String substring) {
        return str.contains(substring);
    }

    // Counts occurrences of a character in a string
    public static int countCharacters(String str, char character) {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == character) {
                count++;
            }
        }
        return count;
    }
}

In this code:

  • The reverseString function reverses the input string.
  • The containsSubstring function checks if a substring exists in the original string.
  • The countCharacters function counts the occurrences of a specified character in the original string.

The main method demonstrates the usage of these string manipulation functions on an example string (“Hello, World!”). You can replace the originalString, searchSubstring, and characterToCount variables with your own input as needed.

image-35 Crack Interview: Top 10 Critical Coding Interview Questions Every Student Must Know!
Top 10 Critical Coding

9 Depth-first search (DFS)

import java.util.*;

public class GraphTraversal {
    private int V; // Number of vertices
    private LinkedList<Integer> adj[]; // Adjacency list representation

    // Constructor to initialize the graph
    GraphTraversal(int v) {
        V = v;
        adj = new LinkedList[v];
        for (int i = 0; i < v; ++i)
            adj[i] = new LinkedList();
    }

    // Add an edge to the graph
    void addEdge(int v, int w) {
        adj[v].add(w);
    }

    // Depth-First Search (DFS) traversal starting from a given vertex
    void DFS(int v) {
        boolean visited[] = new boolean[V];
        DFSUtil(v, visited);
    }

    void DFSUtil(int v, boolean visited[]) {
        visited[v] = true;
        System.out.print(v + " ");

        for (Integer n : adj[v]) {
            if (!visited[n]) {
                DFSUtil(n, visited);
            }
        }
    }

    // Breadth-First Search (BFS) traversal starting from a given vertex
    void BFS(int v) {
        boolean visited[] = new boolean[V];
        LinkedList<Integer> queue = new LinkedList<>();

        visited[v] = true;
        queue.add(v);

        while (queue.size() != 0) {
            v = queue.poll();
            System.out.print(v + " ");

            for (Integer n : adj[v]) {
                if (!visited[n]) {
                    visited[n] = true;
                    queue.add(n);
                }
            }
        }
    }

    // Find the shortest path from a source vertex to a destination vertex using BFS
    int shortestPath(int src, int dest) {
        boolean visited[] = new boolean[V];
        int dist[] = new int[V];
        Arrays.fill(dist, -1);

        LinkedList<Integer> queue = new LinkedList<>();

        visited[src] = true;
        dist[src] = 0;
        queue.add(src);

        while (!queue.isEmpty()) {
            int u = queue.poll();

            for (int n : adj[u]) {
                if (!visited[n]) {
                    visited[n] = true;
                    dist[n] = dist[u] + 1;
                    queue.add(n);

                    if (n == dest) {
                        return dist[n];
                    }
                }
            }
        }

        return -1; // If there is no path from src to dest
    }

    public static void main(String[] args) {
        GraphTraversal graph = new GraphTraversal(8);

        graph.addEdge(0, 1);
        graph.addEdge(0, 2);
        graph.addEdge(1, 3);
        graph.addEdge(1, 4);
        graph.addEdge(2, 5);
        graph.addEdge(2, 6);
        graph.addEdge(4, 7);

        System.out.println("Depth-First Search (DFS) starting from vertex 0:");
        graph.DFS(0);

        System.out.println("\n\nBreadth-First Search (BFS) starting from vertex 0:");
        graph.BFS(0);

        int src = 0, dest = 7;
        int shortestDistance = graph.shortestPath(src, dest);
        System.out.println("\n\nShortest distance from vertex " + src + " to vertex " + dest + ": " + shortestDistance);
    }
}

In this code:

  • GraphTraversal represents a graph with methods for adding edges, performing depth-first search (DFS), breadth-first search (BFS), and finding the shortest path using BFS.
  • The main method demonstrates the usage of these graph traversal algorithms on a sample graph with 8 vertices and edges.
  • You can modify the graph and source/destination vertices as needed to test different scenarios.
  • Top 10 Critical Coding
See also  Shopping Cart using Spring Boot with source code

10 Recursion Practice

Here’s a complete Java program that solves the Tower of Hanoi problem using recursion:

import java.util.Scanner;

public class TowerOfHanoi {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of disks: ");
        int numDisks = scanner.nextInt();
        scanner.close();

        towerOfHanoi(numDisks, 'A', 'C', 'B');
    }

    public static void towerOfHanoi(int n, char source, char destination, char auxiliary) {
        if (n == 1) {
            System.out.println("Move disk 1 from " + source + " to " + destination);
            return;
        }

        towerOfHanoi(n - 1, source, auxiliary, destination);
        System.out.println("Move disk " + n + " from " + source + " to " + destination);
        towerOfHanoi(n - 1, auxiliary, destination, source);
    }
}

In this code:

  • The main method takes user input for the number of disks in the Tower of Hanoi puzzle.
  • The towerOfHanoi method is a recursive function that solves the Tower of Hanoi problem. It takes three parameters: n (the number of disks), source (the source peg), destination (the destination peg), and auxiliary (the auxiliary peg).
  • The towerOfHanoi function prints the steps to move the disks from the source peg to the destination peg while using the auxiliary peg as an intermediate step.

When you run the program and enter the number of disks, it will display the steps required to solve the Tower of Hanoi puzzle with that number of disks.

Java Projects Video :Click here
https://updategadh.com/chatcpt/create-a-chatbot-with-openai-chatgpt/

Top 10 Critical Coding Top 10 Critical Coding Top 10 Critical Coding Top 10 Critical Coding Top 10 Critical Coding Top 10 Critical Coding Top 10 Critical Coding Top 10 Critical Coding Top 10 Critical Coding Top 10 Critical Coding

1 comment

Post Comment