fbpx

Top 100 Amazon SDE Interview Questions and Answers

Top 100 Amazon SDE Interview Questions and Answers

Contents show

1. Explain the Time Complexity of Quick Sort Algorithm.

Quick Sort has an average-case time complexity of O(n log n) and a worst-case time complexity of O(n^2) when the pivot is not chosen well. It’s a widely used algorithm due to its efficiency and simplicity. Official Reference


2. How Does a Hash Map Work?

A HashMap uses a hash function to convert keys into array indices. It provides constant-time average complexity for basic operations like get() and put(). In case of collisions, a linked list or a balanced tree is used. Official Reference


3. Write a Function to Find the Nth Fibonacci Number.

def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)

This recursive function returns the Nth Fibonacci number efficiently. Official Reference


4. What is the Difference Between an Abstract Class and an Interface?

An abstract class can have method implementations and variables, while an interface only declares method signatures. A class can implement multiple interfaces but can extend only one abstract class. Official Reference


5. Explain the Singleton Design Pattern.

Singleton ensures a class has only one instance and provides a global point of access. It’s implemented by making the class’s constructor private and providing a static method to get the instance. Official Reference


6. Write a Program to Reverse a Linked List.

public ListNode reverseList(ListNode head) {
    ListNode prev = null;
    while (head != null) {
        ListNode next = head.next;
        head.next = prev;
        prev = head;
        head = next;
    }
    return prev;
}

This Java program reverses a singly linked list in-place. Official Reference


7. Explain the CAP Theorem.

CAP theorem states that it’s impossible for a distributed system to simultaneously achieve Consistency (C), Availability (A), and Partition tolerance (P). In case of network failures, you have to choose between C and A. Official Reference


8. How Does Garbage Collection Work in Java?

Garbage collection automatically reclaims memory by freeing objects that are no longer reachable. It uses different algorithms (e.g., Mark and Sweep) to identify and clear unused objects. Official Reference


9. Implement a Depth-First Search Algorithm.

def dfs(graph, start):
    visited = set()
    stack = [start]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.add(vertex)
            stack.extend(graph[vertex] - visited)
    return visited

This Python code performs a depth-first search on a graph. Official Reference


10. What is RESTful API Design?

RESTful API design follows a set of principles that enable stateless, scalable, and discoverable communication between clients and servers. It utilizes standard HTTP methods (GET, POST, PUT, DELETE) and is resource-centric. Official Reference


11. Explain the Observer Design Pattern.

The Observer pattern defines a one-to-many dependency between objects. When one object changes state, all its dependents are notified and updated automatically. It’s widely used in event-driven architectures. Official Reference


12. Write a Function to Check if a Binary Tree is Balanced.

public boolean isBalanced(TreeNode root) {
    return getHeight(root) != -1;
}

private int getHeight(TreeNode node) {
    if (node == null) return 0;
    int left = getHeight(node.left);
    if (left == -1) return -1;
    int right = getHeight(node.right);
    if (right == -1) return -1;
    return Math.abs(left - right) <= 1 ? Math.max(left, right) + 1 : -1;
}

This Java code checks if a binary tree is balanced. Official Reference


13. Explain Big O Notation.

Big O notation is a way to describe the performance or complexity of an algorithm. It represents the upper bound of the time or space required by the algorithm in the worst-case scenario. Official Reference


14. How Does a B-Tree Work?

A B-tree is a self-balancing tree data structure that maintains sorted data and allows searches, sequential access, and insertions in logarithmic time. It’s commonly used in databases and file systems. Official Reference


15. Implement a Priority Queue.

import java.util.PriorityQueue;

PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(5);
pq.add(3);
pq.add(8);
int top = pq.poll(); // Retrieves and removes the minimum element (here, top = 3)

This Java code demonstrates a basic usage of a priority queue. Official Reference


16. Explain the Dijkstra’s Algorithm.

Dijkstra’s algorithm finds the shortest path between nodes in a weighted graph. It maintains a priority queue to greedily select the next node with the smallest known distance. Official Reference


17. What is a Deadlock in Multithreading?

A deadlock is a state where two or more threads are blocked forever, each waiting for the other to release a lock. It’s a critical issue in concurrent programming. Official Reference


18. Write a Program to Find the Longest Common Prefix in an Array of Strings.

def longestCommonPrefix(strs):
    if not strs: return ""
    min_len = min(len(s) for s in strs)
    for i in range(min_len):
        if any(s[i] != strs[0][i] for s in strs):
            return strs[0][:i]
    return strs[0][:min_len]

This Python code finds the longest common prefix in an array of strings. Official Reference


19. Explain the SOLID Principles in Object-Oriented Design.

SOLID is an acronym for five design principles that aim to make software more maintainable, scalable, and adaptable. They are: Single Responsibility, Open-Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. Official Reference


20. How Does Virtual Memory Work?

Virtual memory allows an operating system to use a portion of a storage medium as if it were additional RAM. It swaps data between RAM and disk to ensure all active processes have enough memory to run. Official Reference


21. Write a Program to Find the Intersection of Two Arrays.

public int[] intersect(int[] nums1, int[] nums2) {
    Arrays.sort(nums1);
    Arrays.sort(nums2);
    List<Integer> result = new ArrayList<>();
    int i = 0, j = 0;
    while (i < nums1.length && j < nums2.length) {
        if (nums1[i] == nums2[j]) {
            result.add(nums1[i]);
            i++;
            j++;
        } else if (nums1[i] < nums2[j]) {
            i++;
        } else {
            j++;
        }
    }
    return result.stream().mapToInt(Integer::intValue).toArray();
}

This Java code finds the intersection of two arrays. Official Reference


22. Explain the Flyweight Design Pattern.

The Flyweight pattern is used to minimize memory usage or computational expenses by sharing as much as possible with related objects. It’s particularly useful when dealing with a large number of similar objects. Official Reference


23. What is a ThreadPoolExecutor?

ThreadPoolExecutor is a class in Java that provides a way to manage a pool of worker threads. It automatically reuses threads and handles thread creation, termination, and scheduling. Official Reference


24. Write a Program to Check if a Binary Tree is a Binary Search Tree.

public boolean isValidBST(TreeNode root) {
    return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
}

private boolean isValidBST(TreeNode node, long min, long max) {
    if (node == null) return true;
    if (node.val <= min || node.val >= max) return false;
    return isValidBST(node.left, min, node.val) && isValidBST(node.right, node.val, max);
}

This Java code checks if a binary tree is a valid binary search tree. Official Reference


25. Explain the Producers-Consumers Problem.

The Producers-Consumers problem is a classic synchronization problem where multiple threads are producing and consuming data from a shared buffer. It requires careful handling of thread interactions to prevent race conditions. Official Reference


26. What is the Purpose of the MVC Design Pattern?

The Model-View-Controller (MVC) design pattern separates the application logic into three interconnected components: the Model (data and business logic), the View (presentation layer), and the Controller (user interface logic). It enhances modularity and maintainability. Official Reference


27. Write a Program to Implement a Stack using Linked List.

class ListNode {
    int val;
    ListNode next;
    public ListNode(int val) {
        this.val = val;
    }
}

class MyStack {
    ListNode head;

    public void push(int x) {
        ListNode newNode = new ListNode(x);
        newNode.next = head;
        head = newNode;
    }

    public int pop() {
        if (head == null) throw new IllegalStateException("Stack is empty");
        int val = head.val;
        head = head.next;
        return val;
    }

    public int peek() {
        if (head == null) throw new IllegalStateException("Stack is empty");
        return head.val;
    }

    public boolean isEmpty() {
        return head == null;
    }
}

This Java program implements a stack using a linked list. Official Reference


28. Explain the Proxy Design Pattern.

The Proxy pattern provides a surrogate or placeholder for another object to control access to it. It can be used for various purposes like security, caching, and lazy loading. Official Reference


29. What is a Volatile Keyword in Java?

The volatile keyword in Java is used to indicate that a variable may change asynchronously. It ensures that any read of the variable will be directly from memory, rather than from a cache. Official Reference


30. Write a Program to Perform a Binary Search.

public int binarySearch(int[] nums, int target) {
    int left = 0, right = nums.length - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) return mid;
        if (nums[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    return -1;
}

This Java code performs a binary search in a sorted array. Official Reference


31. Explain the Adapter Design Pattern.

The Adapter pattern allows the interface of an existing class to be used as another interface. It’s often used to make existing classes work with others without modifying their source code. Official Reference


32. What is a Race Condition?

A race condition is a situation in a multithreaded program where two or more threads are trying to access shared data or resources in an unpredictable order. This can lead to incorrect behavior. Official Reference


33. Write a Program to Calculate the Factorial of a Number.

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)
}

This Python code calculates the factorial of a number using recursion. Official Reference


34. Explain the Decorator Design Pattern.

The Decorator pattern allows behavior to be added to individual objects, either statically or dynamically, without affecting the behavior of other objects from the same class. It’s used to extend functionalities in a flexible way. Official Reference


35. How Does the Garbage Collector Work in C#?

In C#, the Garbage Collector manages the allocation and release of memory for your application. It automatically identifies and removes unused objects, making memory management more efficient. Official Reference


36. Write a Program to Find the Missing Number in an Array of Numbers.

public int missingNumber(int[] nums) {
    int n = nums.length;
    int totalSum = n * (n + 1) / 2;
    int actualSum = 0;
    for (int num : nums) {
        actualSum += num;
    }
    return totalSum - actualSum;
}

This Java code finds the missing number in an array of numbers. Official Reference


37. Explain the State Design Pattern.

The State pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class. It’s useful in scenarios with different states and transitions. Official Reference


38. What is the Purpose of a Semaphore?

A Semaphore is a synchronization primitive that allows a fixed number of threads to access a resource concurrently. It’s used to control access to a shared resource and prevent race conditions. Official Reference


39. Write a Program to Check if a String is a Palindrome.

def isPalindrome(s):
    s = ''.join(e for e in s if e.isalnum()).lower()
    return s == s[::-1]
}

This Python code checks if a string is a palindrome. Official Reference


40. Explain the Factory Method Design Pattern.

The Factory Method pattern defines an interface for creating an object, but it lets subclasses alter the type of objects that will be created. It’s used when a class can’t anticipate the class of objects it needs to create. Official Reference


41. How Does a Memory Leak Occur?

A memory leak occurs when a program allocates memory dynamically but fails to release it. This leads to a gradual reduction in available memory, potentially causing the program to crash. Official Reference


42. Write a Program to Find the Largest Element in an Array.

public int findMax(int[] nums) {
    int max = Integer.MIN_VALUE;
    for (int num : nums) {
        if (num > max) {
            max = num;
        }
    }
    return max;
}

This Java code finds the largest element in an array. Official Reference


43. Explain the Builder Design Pattern.

The Builder pattern separates the construction of a complex object from its representation. It’s useful when an object has a large number of possible configurations and it’s not feasible to create a constructor for every combination. Official Reference


44. What is the Purpose of the try-catch Block?

The try-catch block is used in exception handling to handle exceptions that may occur during the execution of a program. Code inside the try block is monitored, and if an exception occurs, it’s caught by the catch block, allowing the program to continue running. Official Reference


45. Write a Program to Perform Matrix Multiplication.

public int[][] multiply(int[][] A, int[][] B) {
    int m = A.length, n = A[0].length, p = B[0].length;
    int[][] result = new int[m][p];
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < p; j++) {
            for (int k = 0; k < n; k++) {
                result[i][j] += A[i][k] * B[k][j];
            }
        }
    }
    return result;
}

This Java code performs matrix multiplication. Official Reference


46. Explain the Strategy Design Pattern.

The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It allows the algorithm to vary independently from the client that uses it. Official Reference


47. How Does Inheritance Work in Object-Oriented Programming?

Inheritance is a fundamental concept in object-oriented programming (OOP) where a class inherits the attributes and behaviors of another class. It allows for code reusability and is a key aspect of polymorphism. Official Reference


48. Write a Program to Find the GCD (Greatest Common Divisor) of Two Numbers.

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a
}

This Python code finds the greatest common divisor of two numbers using Euclid’s algorithm. Official Reference


49. Explain the Memento Design Pattern.

The Memento pattern provides the ability to restore an object to its previous state. It’s particularly useful when you want to implement an undo feature or maintain a history of changes. Official Reference


50. What is the Purpose of the volatile Keyword in C++?

In C++, the volatile keyword is used to indicate that a variable may be modified by something external to the program. It prevents the compiler from applying certain optimizations to that variable. Official Reference


51. Write a Program to Find the Power of a Number.

public double power(double x, int n) {
    if (n == 0) return 1;
    if (n < 0) {
        x = 1 / x;
        n = -n;
    }
    return n % 2 == 0 ? power(x * x, n / 2) : x * power(x * x, n / 2);
}

This Java code calculates the power of a number efficiently. Official Reference


52. Explain the Chain of Responsibility Design Pattern.

The Chain of Responsibility pattern passes a request along a chain of handlers. Upon receiving a request, each handler decides either to process it or pass it along. It’s useful when there are multiple objects that can handle a request. Official Reference


53. What is Polymorphism in Object-Oriented Programming?

Polymorphism allows objects to be treated as instances of their base class, even if they are actually instances of derived classes. This enables flexibility and extensibility in code. Official Reference


54. Write a Program to Perform a Depth-First Search on a Graph.

import java.util.*;

class Graph {
    private int V;
    private LinkedList<Integer> adj[];

    Graph(int v) {
        V = v;
        adj = new LinkedList[v];
        for (int i=0; i<v; ++i)
            adj[i] = new LinkedList();
    }

    void addEdge(int v, int w) {
        adj[v].add(w);
    }

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

        Iterator<Integer> i = adj[v].listIterator();
        while (i.hasNext()) {
            int n = i.next();
            if (!visited[n])
                DFSUtil(n, visited);
        }
    }

    void DFS(int v) {
        boolean visited[] = new boolean[V];
        DFSUtil(v, visited);
    }
}

This Java code performs a depth-first search on a graph. Official Reference


55. Explain the Observer/Observable Pattern in Java.

The Observer pattern defines a one-to-many dependency between objects. When one object changes state, all its dependents are notified and updated automatically. It’s widely used in event-driven architectures. Official Reference


56. What is the Purpose of the static Keyword in C++?

In C++, the static keyword can be applied to variables, functions, and classes. When applied to variables, it makes them retain their value across multiple invocations. When applied to functions or classes, it limits their scope to the file they’re defined in. Official Reference


57. Write a Program to Find the Sum of Digits in a Number.

def sum_of_digits(n):
    total = 0
    while n > 0:
        total += n % 10
        n //= 10
    return total
}

This Python code finds the sum of digits in a number. Official Reference


58. Explain the Visitor Design Pattern.

The Visitor pattern represents an operation to be performed on elements of an object structure. It lets you define a new operation without changing the classes of the elements on which it operates. Official Reference


59. What is the Purpose of the const Keyword in C++?

In C++, the const keyword is used to specify that a variable, method, or pointer is constant and cannot be modified. It ensures that the value won’t be changed accidentally. Official Reference


60. Write a Program to Check if a Year is a Leap Year.

def is_leap_year(year):
    if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
        return True
    else:
        return False
}

This Python code checks if a year is a leap year. Official Reference


61. Explain the Command Design Pattern.

The Command pattern turns a request into a standalone object. This decouples sender and receiver, allowing for parameterization and queuing of requests. It’s useful in scenarios with undo functionality or remote invocations. Official Reference


62. How Does Method Overloading Work in Java?

Method overloading in Java allows a class to have multiple methods with the same name but different parameters. The compiler determines which method to call based on the number or type of arguments. Official Reference


63. Write a Program to Find the LCM (Least Common Multiple) of Two Numbers.

public int lcm(int a, int b) {
    return (a * b) / gcd(a, b);
}

public int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

This Java code finds the least common multiple of two numbers. Official Reference


64. Explain the Mediator Design Pattern.

The Mediator pattern defines an object that centralizes communication between objects in a system. It promotes loose coupling by ensuring that objects don’t communicate directly with each other, but through the mediator. Official Reference


65. What is the Purpose of the final Keyword in Java?

In Java, the final keyword is used to restrict the user. It can be applied to variables, methods, and classes. A final variable can’t be changed, a final method can’t be overridden, and a final class can’t be extended. Official Reference


66. Write a Program to Find the Square Root of a Number.

public double sqrt(double x) {
    if (x < 0) throw new IllegalArgumentException("Input must be non-negative");
    double epsilon = 1e-15;
    double guess = x;
    while (Math.abs(guess - x/guess) > epsilon*guess) {
        guess = (x/guess + guess) / 2.0;
    }
    return guess;
}

This Java code calculates the square root of a number using Newton’s method. Official Reference


67. Explain the Template Method Design Pattern.

The Template Method pattern defines the skeleton of an algorithm but lets subclasses override specific steps of the algorithm without changing its structure. It’s useful when you want to define a general algorithm with specific implementation details left to subclasses. Official Reference


68. How Does Dynamic Memory Allocation Work in C++?

Dynamic memory allocation in C++ is performed using operators new (for allocation) and delete (for deallocation). It allows the program to allocate memory dynamically at runtime, enabling flexibility in memory management. Official Reference


69. Write a Program to Reverse a String.

def reverse_string(s):
    return s[::-1]
}

This Python code reverses a string. Official Reference


70. Explain the Composite Design Pattern.

The Composite pattern lets you compose objects into tree structures to represent part-whole hierarchies. It allows clients to treat individual objects and compositions of objects uniformly. Official Reference


71

. What is the Purpose of the volatile Keyword in C?

In C, the volatile keyword is used to indicate that a variable may change asynchronously. It ensures that any read of the variable will be directly from memory, rather than from a cache. Official Reference


72. Write a Program to Implement a Queue using Stacks.

import java.util.Stack;

class MyQueue {
    private Stack<Integer> inStack;
    private Stack<Integer> outStack;

    public MyQueue() {
        inStack = new Stack<>();
        outStack = new Stack<>();
    }

    public void enqueue(int x) {
        inStack.push(x);
    }

    public int dequeue() {
        if (outStack.isEmpty()) {
            while (!inStack.isEmpty()) {
                outStack.push(inStack.pop());
            }
        }
        return outStack.pop();
    }

    public int peek() {
        if (outStack.isEmpty()) {
            while (!inStack.isEmpty()) {
                outStack.push(inStack.pop());
            }
        }
        return outStack.peek();
    }

    public boolean isEmpty() {
        return inStack.isEmpty() && outStack.isEmpty();
    }
}

This Java program implements a queue using two stacks. Official Reference


73. Explain the Iterator Design Pattern.

The Iterator pattern provides a way to access elements of an aggregate object sequentially without exposing its underlying representation. It’s used to traverse collections in a generic way. Official Reference


74. How Does Memory Allocation for Objects Work in Java?

In Java, objects are dynamically allocated on the heap. When you create an object using the new keyword, memory is allocated on the heap, and a reference to that memory location is returned. The garbage collector manages deallocation of memory. Official Reference


75. Write a Program to Find the First Non-Repeating Character in a String.

def first_non_repeating_char(s):
    char_count = {}
    for char in s:
        if char in char_count:
            char_count[char] += 1
        else:
            char_count[char] = 1

    for char in s:
        if char_count[char] == 1:
            return char
    return None
}

This Python code finds the first non-repeating character in a string. Official Reference


76. Explain the State Design Pattern.

The State pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class. It’s useful in scenarios with different states and transitions. Official Reference


77. What is the Purpose of the static Keyword in Java?

In Java, the static keyword is used to create fields and methods that belong to the class itself, rather than to any specific instance. It allows them to be shared among all instances of the class. Official Reference


78. Write a Program to Check if a String is a Palindrome.

public boolean isPalindrome(String s) {
    s = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
    int left = 0, right = s.length() - 1;
    while (left < right) {
        if (s.charAt(left++) != s.charAt(right--)) return false;
    }
    return true;
}

This Java code checks if a string is a palindrome. Official Reference


79. Explain the Factory Method Design Pattern.

The Factory Method pattern defines an interface for creating an object, but it lets subclasses alter the type of objects that will be created. It’s used when a class can’t anticipate the class of objects it needs to create. Official Reference


80. How Does Method Overloading Work in C++?

Method overloading in C++ allows a class to have multiple methods with the same name but different parameters. The compiler determines which method to call based on the number or type of arguments. Official Reference


81. Write a Program to Find the LCM (Least Common Multiple) of Two Numbers.

def lcm(a, b):
    from math import gcd
    return (a * b) // gcd(a, b)
}

This Python code finds the least common multiple of two numbers. Official Reference


82. Explain the Composite Design Pattern.

The Composite pattern lets you compose objects into tree structures to represent part-whole hierarchies. It allows clients to treat individual objects and compositions of objects uniformly. Official Reference


83. What is the Purpose of the volatile Keyword in C?

In C, the volatile keyword is used to indicate that a variable may change asynchronously. It ensures that any read of the variable will be directly from memory, rather than from a cache. Official Reference


84. Write a Program to Implement a Queue using Stacks.

class MyQueue:
    def __init__(self):
        self.in_stack = []
        self.out_stack = []

    def enqueue(self, x):
        self.in_stack.append(x)

    def dequeue(self):
        if not self.out_stack:
            while self.in_stack:
                self.out_stack.append(self.in_stack.pop())
        return self.out_stack.pop()

    def peek(self):
        if not self.out_stack:
            while self.in_stack:
                self.out_stack.append(self.in_stack.pop())
        return self.out_stack[-1]

    def is_empty(self):
        return not self.in_stack and not self.out_stack

This Python program implements a queue using two stacks. Official Reference


85. Explain the Iterator Design Pattern.

The Iterator pattern provides a way to access elements of an aggregate object sequentially without exposing its underlying representation. It’s used to traverse collections in a generic way. Official Reference


86. How Does Memory Allocation for Objects Work in Java?

In Java, objects are dynamically allocated on the heap. When you create an object using the new keyword, memory is allocated on the heap, and a reference to that memory location is returned. The garbage collector manages deal location of memory. Official Reference


87. Write a Program to Find the First Non-Repeating Character in a String.

public char firstNonRepeatingChar(String s) {
    int[] charCount = new int[256];
    for (char c : s.toCharArray()) {
        charCount[c]++;
    }
    for (char c : s.toCharArray()) {
        if (charCount[c] == 1) return c;
    }
    return '\0';
}

This Java code finds the first non-repeating character in a string. Official Reference


88. Explain the State Design Pattern.

The State pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class. It’s useful in scenarios with different states and transitions. Official Reference


89. What is the Purpose of the static Keyword in Java?

In Java, the static keyword is used to create fields and methods that belong to the class itself, rather than to any specific instance. It allows them to be shared among all instances of the class. Official Reference


90. Write a Program to Check if a String is a Palindrome.

public boolean isPalindrome(String s) {
    s = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
    int left = 0, right = s.length() - 1;
    while (left < right) {
        if (s.charAt(left++) != s.charAt(right--)) return false;
    }
    return true;
}

This Java code checks if a string is a palindrome. Official Reference


91. Explain the Factory Method Design Pattern.

The Factory Method pattern defines an interface for creating an object, but it lets subclasses alter the type of objects that will be created. It’s used when a class can’t anticipate the class of objects it needs to create. Official Reference


92. How Does Method Overloading Work in C++?

Method overloading in C++ allows a class to have multiple methods with the same name but different parameters. The compiler determines which method to call based on the number or type of arguments. Official Reference


93. Write a Program to Find the LCM (Least Common Multiple) of Two Numbers.

def lcm(a, b):
    from math import gcd
    return (a * b) // gcd(a, b)
}

This Python code finds the least common multiple of two numbers. Official Reference


94. Explain the Composite Design Pattern.

The Composite pattern lets you compose objects into tree structures to represent part-whole hierarchies. It allows clients to treat individual objects and compositions of objects uniformly. Official Reference


95. What is the Purpose of the volatile Keyword in C?

In C, the volatile keyword is used to indicate that a variable may change asynchronously. It ensures that any read of the variable will be directly from memory, rather than from a cache. Official Reference


96. Write a Program to Implement a Queue using Stacks.

class MyQueue:
    def __init__(self):
        self.in_stack = []
        self.out_stack = []

    def enqueue(self, x):
        self.in_stack.append(x)

    def dequeue(self):
        if not self.out_stack:
            while self.in_stack:
                self.out_stack.append(self.in_stack.pop())
        return self.out_stack.pop()

    def peek(self):
        if not self.out_stack:
            while self.in_stack:
                self.out_stack.append(self.in_stack.pop())
        return self.out_stack[-1]

    def is_empty(self):
        return not self.in_stack and not self.out_stack

This Python program implements a queue using two stacks. Official Reference


97. Explain the Iterator Design Pattern.

The Iterator pattern provides a way to access elements of an aggregate object sequentially without exposing its underlying representation. It’s used to traverse collections in a generic way. Official Reference


98. How Does Memory Allocation for Objects Work in Java?

In Java, objects are dynamically allocated on the heap. When you create an object using the new keyword, memory is allocated on the heap, and a reference to that memory location is returned. The garbage collector manages deallocation of memory. Official Reference


99. Write a Program to Find the First Non-Repeating Character in a String.

public char firstNonRepeatingChar(String s) {
    int[] charCount = new int[256];
    for (char c : s.toCharArray()) {
        charCount[c]++;
    }
    for (char c : s.toCharArray()) {
        if (charCount[c] == 1) return c;
    }
    return '\0';
}

This Java code finds the first non-repeating character in a string. Official Reference


100. Explain the State Design Pattern.

The State pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class. It’s useful in scenarios with different states and transitions. Official Reference