50 Most Common Coding Interview Questions -
Explanations Guide
Q1. Reverse a String
Explanation: This question tests fundamental concepts related to Q1. Reverse a String.
Understand the approach, time complexity, edge cases, and be able to explain why the chosen
solution works during interviews.
Code:
public class ReverseString { public static String reverse(String str) {
char[] chars = [Link](); int left = 0, right = [Link] - 1;
while (left < right) { char temp = chars[left]; chars[left] =
chars[right]; chars[right] = temp; left++; right--; } return new
String(chars); } public static void main(String[] args) {
[Link](reverse("hello")); // olleh } }
Q2. Check if a String is a Palindrome
Explanation: This question tests fundamental concepts related to Q2. Check if a String is a
Palindrome. Understand the approach, time complexity, edge cases, and be able to explain why the
chosen solution works during interviews.
Code:
public class PalindromeCheck { public static boolean isPalindrome(String
str) { int left = 0, right = [Link]() - 1; while (left < right) { if
([Link](left) != [Link](right)) return false; left++; right--; }
return true; } public static void main(String[] args) {
[Link](isPalindrome("madam")); // true
[Link](isPalindrome("hello")); // false } }
Q3. Check if Two Strings are Anagrams
Explanation: This question tests fundamental concepts related to Q3. Check if Two Strings are
Anagrams. Understand the approach, time complexity, edge cases, and be able to explain why the
chosen solution works during interviews.
Code:
import [Link]; public class AnagramCheck { public static
boolean isAnagram(String s1, String s2) { if ([Link]() != [Link]())
return false; char[] a = [Link](); char[] b = [Link]();
[Link](a); [Link](b); return [Link](a, b); } public
static void main(String[] args) { [Link](isAnagram("listen",
"silent")); // true } }
Q4. Factorial Using Recursion
Explanation: This question tests fundamental concepts related to Q4. Factorial Using Recursion.
Understand the approach, time complexity, edge cases, and be able to explain why the chosen
solution works during interviews.
Code:
public class Factorial { public static long factorial(int n) { if (n <=
1) return 1; return n * factorial(n - 1); } public static void
main(String[] args) { [Link](factorial(5)); // 120 } }
Q5. Print the Fibonacci Series
Explanation: This question tests fundamental concepts related to Q5. Print the Fibonacci Series.
Understand the approach, time complexity, edge cases, and be able to explain why the chosen
solution works during interviews.
Code:
public class Fibonacci { public static void printFibonacci(int n) { int a
= 0, b = 1; for (int i = 0; i < n; i++) { [Link](a + " "); int
next = a + b; a = b; b = next; } } public static void main(String[] args)
{ printFibonacci(10); // 0 1 1 2 3 5 8 13 21 34 } }
Q6. Check if a Number is Prime
Explanation: This question tests fundamental concepts related to Q6. Check if a Number is Prime.
Understand the approach, time complexity, edge cases, and be able to explain why the chosen
solution works during interviews.
Code:
public class PrimeCheck { public static boolean isPrime(int n) { if (n <
2) return false; for (int i = 2; i * i <= n; i++) { if (n % i == 0) return
false; } return true; } public static void main(String[] args) {
[Link](isPrime(17)); // true } }
Q7. Find the Largest and Smallest Number in an Array
Explanation: This question tests fundamental concepts related to Q7. Find the Largest and
Smallest Number in an Array. Understand the approach, time complexity, edge cases, and be able
to explain why the chosen solution works during interviews.
Code:
public class MinMaxArray { public static void findMinMax(int[] arr) { int
min = arr[0], max = arr[0]; for (int num : arr) { if (num < min) min =
num; if (num > max) max = num; } [Link]("Min: " + min + ",
Max: " + max); } public static void main(String[] args) { findMinMax(new
int[]{5, 3, 9, 1, 7}); // Min: 1, Max: 9 } }
Q8. Remove Duplicates from an Array
Explanation: This question tests fundamental concepts related to Q8. Remove Duplicates from an
Array. Understand the approach, time complexity, edge cases, and be able to explain why the
chosen solution works during interviews.
Code:
import [Link]; import [Link]; public class
RemoveDuplicates { public static int[] removeDuplicates(int[] arr) {
LinkedHashSet<Integer> set = new LinkedHashSet<>(); for (int num : arr)
[Link](num); return [Link]().mapToInt(Integer::intValue).toArray();
} public static void main(String[] args) { int[] result =
removeDuplicates(new int[]{1, 2, 2, 3, 4, 4, 5});
[Link]([Link](result)); // [1, 2, 3, 4, 5] } }
Q9. Implement Bubble Sort
Explanation: This question tests fundamental concepts related to Q9. Implement Bubble Sort.
Understand the approach, time complexity, edge cases, and be able to explain why the chosen
solution works during interviews.
Code:
import [Link]; public class BubbleSort { public static void
sort(int[] arr) { int n = [Link]; for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp
= arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } public static
void main(String[] args) { int[] arr = {5, 2, 8, 1, 9}; sort(arr);
[Link]([Link](arr)); // [1, 2, 5, 8, 9] } }
Q10. Implement Binary Search
Explanation: This question tests fundamental concepts related to Q10. Implement Binary Search.
Understand the approach, time complexity, edge cases, and be able to explain why the chosen
solution works during interviews.
Code:
public class BinarySearch { public static int search(int[] arr, int
target) { int low = 0, high = [Link] - 1; while (low <= high) { int
mid = low + (high - low) / 2; if (arr[mid] == target) return mid; else if
(arr[mid] < target) low = mid + 1; else high = mid - 1; } return -1; }
public static void main(String[] args) { int[] arr = {1, 3, 5, 7, 9, 11};
[Link](search(arr, 7)); // 3 } }
Q11. Reverse a Linked List
Explanation: This question tests fundamental concepts related to Q11. Reverse a Linked List.
Understand the approach, time complexity, edge cases, and be able to explain why the chosen
solution works during interviews.
Code:
class Node { int data; Node next; Node(int data) { [Link] = data; } }
public class ReverseLinkedList { public static Node reverse(Node head) {
Node prev = null, current = head; while (current != null) { Node next =
[Link]; [Link] = prev; prev = current; current = next; }
return prev; } public static void print(Node head) { while (head != null)
{ [Link]([Link] + " -> "); head = [Link]; }
[Link]("null"); } public static void main(String[] args) {
Node head = new Node(1); [Link] = new Node(2); [Link] = new
Node(3); head = reverse(head); print(head); // 3 -> 2 -> 1 -> null } }
Q12. Detect a Cycle in a Linked List (Floyd's Algorithm)
Explanation: This question tests fundamental concepts related to Q12. Detect a Cycle in a Linked
List (Floyd's Algorithm). Understand the approach, time complexity, edge cases, and be able to
explain why the chosen solution works during interviews.
Code:
// Reuses the Node class from Q11 public class CycleDetection { public
static boolean hasCycle(Node head) { Node slow = head, fast = head; while
(fast != null && [Link] != null) { slow = [Link]; fast =
[Link]; if (slow == fast) return true; } return false; } }
Q13. Implement a Stack Using an Array
Explanation: This question tests fundamental concepts related to Q13. Implement a Stack Using
an Array. Understand the approach, time complexity, edge cases, and be able to explain why the
chosen solution works during interviews.
Code:
public class ArrayStack { private int[] data; private int top; public
ArrayStack(int capacity) { data = new int[capacity]; top = -1; } public
void push(int value) { if (top == [Link] - 1) throw new
RuntimeException("Stack Overflow"); data[++top] = value; } public int
pop() { if (top == -1) throw new RuntimeException("Stack Underflow");
return data[top--]; } public int peek() { return data[top]; } public
boolean isEmpty() { return top == -1; } public static void main(String[]
args) { ArrayStack stack = new ArrayStack(5); [Link](1);
[Link](2); [Link]([Link]()); // 2 } }
Q14. Two Sum Problem
Explanation: This question tests fundamental concepts related to Q14. Two Sum Problem.
Understand the approach, time complexity, edge cases, and be able to explain why the chosen
solution works during interviews.
Code:
import [Link]; public class TwoSum { public static int[]
twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new
HashMap<>(); for (int i = 0; i < [Link]; i++) { int complement =
target - nums[i]; if ([Link](complement)) { return new
int[]{[Link](complement), i}; } [Link](nums[i], i); } throw new
IllegalArgumentException("No solution found"); } public static void
main(String[] args) { int[] result = twoSum(new int[]{2, 7, 11, 15}, 9);
[Link](result[0] + ", " + result[1]); // 0, 1 } }
Q15. Singleton Design Pattern (Thread-Safe)
Explanation: This question tests fundamental concepts related to Q15. Singleton Design Pattern
(Thread-Safe). Understand the approach, time complexity, edge cases, and be able to explain why
the chosen solution works during interviews.
Code:
public class Singleton { private static volatile Singleton instance;
private Singleton() {} public static Singleton getInstance() { if
(instance == null) { synchronized ([Link]) { if (instance ==
null) { instance = new Singleton(); } } } return instance; } }
Q16. Producer-Consumer Problem Using wait()/notify()
Explanation: This question tests fundamental concepts related to Q16. Producer-Consumer
Problem Using wait()/notify(). Understand the approach, time complexity, edge cases, and be able
to explain why the chosen solution works during interviews.
Code:
import [Link]; public class ProducerConsumer { private
final LinkedList<Integer> queue = new LinkedList<>(); private final int
capacity = 5; public void produce() throws InterruptedException { int
value = 0; while (true) { synchronized (this) { while ([Link]() ==
capacity) wait(); [Link](value); [Link]("Produced: " +
value++); notify(); [Link](500); } } } public void consume() throws
InterruptedException { while (true) { synchronized (this) { while
([Link]()) wait(); int value = [Link]();
[Link]("Consumed: " + value); notify(); [Link](800); }
} } public static void main(String[] args) { ProducerConsumer pc = new
ProducerConsumer(); new Thread(() -> { try { [Link](); } catch
(InterruptedException e) {} }).start(); new Thread(() -> { try {
[Link](); } catch (InterruptedException e) {} }).start(); } }
Q17. Override equals() and hashCode()
Explanation: This question tests fundamental concepts related to Q17. Override equals() and
hashCode(). Understand the approach, time complexity, edge cases, and be able to explain why
the chosen solution works during interviews.
Code:
import [Link]; public class Employee { private int id; private
String name; public Employee(int id, String name) { [Link] = id;
[Link] = name; } @Override public boolean equals(Object o) { if (this
== o) return true; if (!(o instanceof Employee)) return false; Employee
emp = (Employee) o; return id == [Link] && [Link](name,
[Link]); } @Override public int hashCode() { return [Link](id,
name); } }
Q18. Find the Nth Highest Salary
Explanation: This question tests fundamental concepts related to Q18. Find the Nth Highest
Salary. Understand the approach, time complexity, edge cases, and be able to explain why the
chosen solution works during interviews.
Code:
-- Simple approach (MySQL/Postgres) SELECT salary FROM employees ORDER BY
salary DESC LIMIT 1 OFFSET 2; -- OFFSET 2 = 3rd highest salary --
Portable approach using window functions SELECT salary FROM ( SELECT
salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees )
ranked WHERE rnk = 3; -- 3rd highest
Q19. Find Duplicate Records in a Table
Explanation: This question tests fundamental concepts related to Q19. Find Duplicate Records in
a Table. Understand the approach, time complexity, edge cases, and be able to explain why the
chosen solution works during interviews.
Code:
SELECT name, email, COUNT(*) AS occurrences FROM employees GROUP BY name,
email HAVING COUNT(*) > 1;
Q20. Department-wise Highest Salary
Explanation: This question tests fundamental concepts related to Q20. Department-wise Highest
Salary. Understand the approach, time complexity, edge cases, and be able to explain why the
chosen solution works during interviews.
Code:
SELECT [Link] AS department, [Link] AS employee, [Link] FROM employees
e JOIN departments d ON e.department_id = [Link] WHERE [Link] = ( SELECT
MAX(salary) FROM employees WHERE department_id = e.department_id );
Q21. Self Join — Employees and Their Managers
Explanation: This question tests fundamental concepts related to Q21. Self Join — Employees
and Their Managers. Understand the approach, time complexity, edge cases, and be able to
explain why the chosen solution works during interviews.
Code:
SELECT [Link] AS employee, [Link] AS manager FROM employees e LEFT JOIN
employees m ON e.manager_id = [Link];
Q22. Employees With No Manager
Explanation: This question tests fundamental concepts related to Q22. Employees With No
Manager. Understand the approach, time complexity, edge cases, and be able to explain why the
chosen solution works during interviews.
Code:
SELECT name FROM employees WHERE manager_id IS NULL;
Q23. Count of Employees per Department
Explanation: This question tests fundamental concepts related to Q23. Count of Employees per
Department. Understand the approach, time complexity, edge cases, and be able to explain why
the chosen solution works during interviews.
Code:
SELECT [Link] AS department, COUNT([Link]) AS total_employees FROM
departments d LEFT JOIN employees e ON [Link] = e.department_id GROUP BY
[Link];
Q24. Delete Duplicate Rows, Keeping One
Explanation: This question tests fundamental concepts related to Q24. Delete Duplicate Rows,
Keeping One. Understand the approach, time complexity, edge cases, and be able to explain why
the chosen solution works during interviews.
Code:
DELETE FROM employees WHERE id NOT IN ( SELECT MIN(id) FROM employees
GROUP BY name, email );
Q25. Employees Who Joined in the Last N Days
Explanation: This question tests fundamental concepts related to Q25. Employees Who Joined in
the Last N Days. Understand the approach, time complexity, edge cases, and be able to explain
why the chosen solution works during interviews.
Code:
SELECT name, join_date FROM employees WHERE join_date >= CURRENT_DATE -
INTERVAL '30 days';
Q26. Running / Cumulative Total Using a Window Function
Explanation: This question tests fundamental concepts related to Q26. Running / Cumulative Total
Using a Window Function. Understand the approach, time complexity, edge cases, and be able to
explain why the chosen solution works during interviews.
Code:
SELECT name, salary, SUM(salary) OVER (ORDER BY id) AS running_total FROM
employees;
Q27. RANK() vs DENSE_RANK() vs ROW_NUMBER()
Explanation: This question tests fundamental concepts related to Q27. RANK() vs
DENSE_RANK() vs ROW_NUMBER(). Understand the approach, time complexity, edge cases,
and be able to explain why the chosen solution works during interviews.
Code:
SELECT name, salary, RANK() OVER (ORDER BY salary DESC) AS rank_val,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rank_val, ROW_NUMBER()
OVER (ORDER BY salary DESC) AS row_num FROM employees;
Q28. Find Common Records Between Two Tables
Explanation: This question tests fundamental concepts related to Q28. Find Common Records
Between Two Tables. Understand the approach, time complexity, edge cases, and be able to
explain why the chosen solution works during interviews.
Code:
SELECT email FROM employees INTERSECT SELECT email FROM contractors; --
Equivalent using JOIN SELECT [Link] FROM employees e JOIN contractors c
ON [Link] = [Link];
Q29. Update Rows Using a Join
Explanation: This question tests fundamental concepts related to Q29. Update Rows Using a Join.
Understand the approach, time complexity, edge cases, and be able to explain why the chosen
solution works during interviews.
Code:
UPDATE employees e JOIN departments d ON e.department_id = [Link] SET
[Link] = [Link] * 1.10 WHERE [Link] = 'Engineering';
Q30. GROUP BY With a HAVING Clause
Explanation: This question tests fundamental concepts related to Q30. GROUP BY With a
HAVING Clause. Understand the approach, time complexity, edge cases, and be able to explain
why the chosen solution works during interviews.
Code:
SELECT department_id, AVG(salary) AS avg_salary FROM employees GROUP BY
department_id HAVING AVG(salary) > 60000;
Q31. Find Gaps in a Sequence of Numbers
Explanation: This question tests fundamental concepts related to Q31. Find Gaps in a Sequence
of Numbers. Understand the approach, time complexity, edge cases, and be able to explain why
the chosen solution works during interviews.
Code:
SELECT id + 1 AS gap_starts_after FROM employees e WHERE NOT EXISTS (
SELECT 1 FROM employees e2 WHERE [Link] = [Link] + 1 ) ORDER BY id;
Q32. Pivot Rows Into Columns
Explanation: This question tests fundamental concepts related to Q32. Pivot Rows Into Columns.
Understand the approach, time complexity, edge cases, and be able to explain why the chosen
solution works during interviews.
Code:
SELECT department_id, SUM(CASE WHEN gender = 'M' THEN 1 ELSE 0 END) AS
male_count, SUM(CASE WHEN gender = 'F' THEN 1 ELSE 0 END) AS female_count
FROM employees GROUP BY department_id;
Q33. Second Highest Salary in Each Department
Explanation: This question tests fundamental concepts related to Q33. Second Highest Salary in
Each Department. Understand the approach, time complexity, edge cases, and be able to explain
why the chosen solution works during interviews.
Code:
SELECT department_id, name, salary FROM ( SELECT department_id, name,
salary, DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary
DESC) AS rnk FROM employees ) ranked WHERE rnk = 2;
Q34. Implement a Debounce Function
Explanation: This question tests fundamental concepts related to Q34. Implement a Debounce
Function. Understand the approach, time complexity, edge cases, and be able to explain why the
chosen solution works during interviews.
Code:
function debounce(fn, delay) { let timer; return function (...args) {
clearTimeout(timer); timer = setTimeout(() => [Link](this, args),
delay); }; } // Usage const log = debounce(() =>
[Link]('Searched!'), 300); [Link]('resize', log);
Q35. Implement a Throttle Function
Explanation: This question tests fundamental concepts related to Q35. Implement a Throttle
Function. Understand the approach, time complexity, edge cases, and be able to explain why the
chosen solution works during interviews.
Code:
function throttle(fn, limit) { let inThrottle; return function (...args)
{ if (!inThrottle) { [Link](this, args); inThrottle = true;
setTimeout(() => (inThrottle = false), limit); } }; }
Q36. Deep Clone an Object
Explanation: This question tests fundamental concepts related to Q36. Deep Clone an Object.
Understand the approach, time complexity, edge cases, and be able to explain why the chosen
solution works during interviews.
Code:
function deepClone(obj) { if (obj === null || typeof obj !== 'object')
return obj; if ([Link](obj)) return [Link](deepClone); const
cloned = {}; for (const key in obj) { if ([Link](key))
cloned[key] = deepClone(obj[key]); } return cloned; } // Modern shortcut
for simple cases: structuredClone(obj)
Q37. Flatten a Nested Array
Explanation: This question tests fundamental concepts related to Q37. Flatten a Nested Array.
Understand the approach, time complexity, edge cases, and be able to explain why the chosen
solution works during interviews.
Code:
function flatten(arr) { return [Link]((flat, item) =>
[Link]([Link](item) ? flatten(item) : item), []); }
[Link](flatten([1, [2, [3, 4], 5], 6])); // [1, 2, 3, 4, 5, 6]
Q38. Implement [Link] (Polyfill)
Explanation: This question tests fundamental concepts related to Q38. Implement
[Link] (Polyfill). Understand the approach, time complexity, edge cases, and be able
to explain why the chosen solution works during interviews.
Code:
[Link] = function (callback) { const result = []; for (let
i = 0; i < [Link]; i++) { [Link](callback(this[i], i, this)); }
return result; }; [Link]([1, 2, 3].myMap(x => x * 2)); // [2, 4, 6]
Q39. Implement [Link] (Polyfill)
Explanation: This question tests fundamental concepts related to Q39. Implement
[Link] (Polyfill). Understand the approach, time complexity, edge cases, and be
able to explain why the chosen solution works during interviews.
Code:
[Link] = function (callback, initialValue) { let
accumulator = initialValue; let startIndex = 0; if (accumulator ===
undefined) { accumulator = this[0]; startIndex = 1; } for (let i =
startIndex; i < [Link]; i++) { accumulator = callback(accumulator,
this[i], i, this); } return accumulator; }; [Link]([1, 2,
3].myReduce((a, b) => a + b, 0)); // 6
Q40. Implement a Custom [Link]
Explanation: This question tests fundamental concepts related to Q40. Implement a Custom
[Link]. Understand the approach, time complexity, edge cases, and be able to explain why the
chosen solution works during interviews.
Code:
function promiseAll(promises) { return new Promise((resolve, reject) => {
if ([Link] === 0) return resolve([]); const results = []; let
completed = 0; [Link]((p, index) => {
[Link](p).then(value => { results[index] = value; completed++;
if (completed === [Link]) resolve(results); }).catch(reject);
}); }); }
Q41. Implement Function Currying
Explanation: This question tests fundamental concepts related to Q41. Implement Function
Currying. Understand the approach, time complexity, edge cases, and be able to explain why the
chosen solution works during interviews.
Code:
function curry(fn) { return function curried(...args) { if ([Link]
>= [Link]) { return [Link](this, args); } return (...next) =>
[Link](this, [...args, ...next]); }; } const add = (a, b, c) => a
+ b + c; const curriedAdd = curry(add); [Link](curriedAdd(1)(2)(3));
// 6
Q42. Counter Component Using useState
Explanation: This question tests fundamental concepts related to Q42. Counter Component Using
useState. Understand the approach, time complexity, edge cases, and be able to explain why the
chosen solution works during interviews.
Code:
import { useState } from 'react'; function Counter() { const [count,
setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button
onClick={() => setCount(count + 1)}>+</button> <button onClick={() =>
setCount(count - 1)}>-</button> </div> ); } export default Counter;
Q43. Fetch Data Using useEffect
Explanation: This question tests fundamental concepts related to Q43. Fetch Data Using
useEffect. Understand the approach, time complexity, edge cases, and be able to explain why the
chosen solution works during interviews.
Code:
import { useState, useEffect } from 'react'; function UserList() { const
[users, setUsers] = useState([]); const [loading, setLoading] =
useState(true); useEffect(() => {
fetch('[Link] .then(res =>
[Link]()) .then(data => { setUsers(data); setLoading(false); }); },
[]); if (loading) return <p>Loading...</p>; return ( <ul> {[Link](user
=> <li key={[Link]}>{[Link]}</li>)} </ul> ); } export default
UserList;
Q44. Build a Custom Hook — useFetch
Explanation: This question tests fundamental concepts related to Q44. Build a Custom Hook —
useFetch. Understand the approach, time complexity, edge cases, and be able to explain why the
chosen solution works during interviews.
Code:
import { useState, useEffect } from 'react'; function useFetch(url) {
const [data, setData] = useState(null); const [error, setError] =
useState(null); const [loading, setLoading] = useState(true);
useEffect(() => { setLoading(true); fetch(url) .then(res => [Link]())
.then(setData) .catch(setError) .finally(() => setLoading(false)); },
[url]); return { data, error, loading }; } export default useFetch;
Q45. Controlled Form Component
Explanation: This question tests fundamental concepts related to Q45. Controlled Form
Component. Understand the approach, time complexity, edge cases, and be able to explain why
the chosen solution works during interviews.
Code:
import { useState } from 'react'; function LoginForm() { const [form,
setForm] = useState({ email: '', password: '' }); const handleChange =
(e) => { setForm({ ...form, [[Link]]: [Link] }); }; const
handleSubmit = (e) => { [Link](); [Link](form); }; return
( <form onSubmit={handleSubmit}> <input name="email" value={[Link]}
onChange={handleChange} /> <input name="password" type="password"
value={[Link]} onChange={handleChange} /> <button
type="submit">Login</button> </form> ); } export default LoginForm;
Q46. Todo List App (Add / Toggle / Delete)
Explanation: This question tests fundamental concepts related to Q46. Todo List App (Add /
Toggle / Delete). Understand the approach, time complexity, edge cases, and be able to explain
why the chosen solution works during interviews.
Code:
import { useState } from 'react'; function TodoApp() { const [todos,
setTodos] = useState([]); const [input, setInput] = useState(''); const
addTodo = () => { if (![Link]()) return; setTodos([...todos, { id:
[Link](), text: input, done: false }]); setInput(''); }; const
toggleTodo = (id) => { setTodos([Link](t => [Link] === id ? { ...t,
done: ![Link] } : t)); }; const deleteTodo = (id) => {
setTodos([Link](t => [Link] !== id)); }; return ( <div> <input
value={input} onChange={e => setInput([Link])} /> <button
onClick={addTodo}>Add</button> <ul> {[Link](t => ( <li key={[Link]}
style={{ textDecoration: [Link] ? 'line-through' : 'none' }}> <span
onClick={() => toggleTodo([Link])}>{[Link]}</span> <button onClick={() =>
deleteTodo([Link])}>x</button> </li> ))} </ul> </div> ); } export default
TodoApp;
Q47. useMemo and useCallback Example
Explanation: This question tests fundamental concepts related to Q47. useMemo and useCallback
Example. Understand the approach, time complexity, edge cases, and be able to explain why the
chosen solution works during interviews.
Code:
import { useState, useMemo, useCallback } from 'react'; function
ExpensiveList({ items }) { const [count, setCount] = useState(0); const
sortedItems = useMemo(() => { [Link]('Sorting...'); return
[...items].sort((a, b) => a - b); }, [items]); const handleClick =
useCallback(() => { setCount(c => c + 1); }, []); return ( <div> <button
onClick={handleClick}>Clicked {count} times</button>
<ul>{[Link](item => <li key={item}>{item}</li>)}</ul> </div> );
} export default ExpensiveList;
Q48. Search / Filter List Component
Explanation: This question tests fundamental concepts related to Q48. Search / Filter List
Component. Understand the approach, time complexity, edge cases, and be able to explain why
the chosen solution works during interviews.
Code:
import { useState } from 'react'; function SearchableList({ items }) {
const [query, setQuery] = useState(''); const filtered =
[Link](item => [Link]().includes([Link]()) );
return ( <div> <input placeholder="Search..." value={query} onChange={e
=> setQuery([Link])} /> <ul> {[Link]((item, i) => <li
key={i}>{item}</li>)} </ul> </div> ); } export default SearchableList;
Q49. Context API Example (Theme Toggle)
Explanation: This question tests fundamental concepts related to Q49. Context API Example
(Theme Toggle). Understand the approach, time complexity, edge cases, and be able to explain
why the chosen solution works during interviews.
Code:
import { createContext, useContext, useState } from 'react'; const
ThemeContext = createContext(); export function ThemeProvider({ children
}) { const [theme, setTheme] = useState('light'); const toggleTheme = ()
=> setTheme(t => (t === 'light' ? 'dark' : 'light')); return (
<[Link] value={{ theme, toggleTheme }}> {children}
</[Link]> ); } function ThemedButton() { const { theme,
toggleTheme } = useContext(ThemeContext); return ( <button
onClick={toggleTheme}> Current theme: {theme} </button> ); }
Q50. Pagination Component
Explanation: This question tests fundamental concepts related to Q50. Pagination Component.
Understand the approach, time complexity, edge cases, and be able to explain why the chosen
solution works during interviews.
Code:
import { useState } from 'react'; function Pagination({ items,
itemsPerPage = 5 }) { const [page, setPage] = useState(1); const
totalPages = [Link]([Link] / itemsPerPage); const currentItems =
[Link]( (page - 1) * itemsPerPage, page * itemsPerPage ); return (
<div> <ul>{[Link]((item, i) => <li key={i}>{item}</li>)}</ul>
<div> {[Link]({ length: totalPages }, (_, i) => ( <button key={i}
onClick={() => setPage(i + 1)} disabled={page === i + 1}> {i + 1}
</button> ))} </div> </div> ); } export default Pagination;