SDE-2

40+ SDE-2 Interview Questions and Answers for Freshers

Updated 20 Jan 2023
search-icon

Q1. Maximum Frequency Number Problem Statement

Given an array of integers with numbers in random order, write a program to find and return the number which appears the most frequently in the array.

If multiple elem...read more

Ans.

Find the number with the maximum frequency in an array of integers.

  • Create a hashmap to store the frequency of each element in the array.

  • Iterate through the array to update the frequency count.

  • Find the element with the maximum frequency and return it.

  • If multiple elements have the same maximum frequency, return the one with the lowest index.

Q2. Remove Consecutive Duplicates from String

Given a string STR consisting of both lower and upper case characters, your task is to remove consecutive duplicate characters and return the newly formed string.

Input...read more

Ans.

The task is to remove consecutive duplicate characters from a given string and return the new string.

  • Iterate through the characters of the string

  • Compare each character with the next character

  • If they are the same, skip the next character

  • If they are different, append the current character to the new string

Q3. Ways To Make Coin Change

Given an infinite supply of coins of varying denominations, determine the total number of ways to make change for a specified value using these coins. If it's not possible to make the c...read more

Ans.

The task is to find the total number of ways to make change for a specified value using given denominations.

  • Use dynamic programming to solve this problem efficiently.

  • Create a 2D array to store the number of ways to make change for each value using different denominations.

  • Iterate through each denomination and update the array based on the number of ways to make change for each value.

  • Return the value at the last cell of the array as the final result.

Frequently asked in,

Q4. Number of Islands Problem Statement

You are provided with a 2-dimensional matrix having N rows and M columns, containing only 1s (land) and 0s (water). Your goal is to determine the number of islands in this ma...read more

Ans.

Count the number of islands in a 2D matrix of 1s and 0s.

  • Use Depth First Search (DFS) or Breadth First Search (BFS) to traverse the matrix and identify connected groups of 1s.

  • Maintain a visited array to keep track of visited cells to avoid revisiting them.

  • Increment the island count each time a new island is encountered.

  • Consider all eight possible directions for connectivity between cells.

  • Handle edge cases like out of bounds indices and water cells (0s).

Are these interview questions helpful?

Q5. Shopping Options Problem Statement

Given arrays representing the costs of pants, shirts, shoes, and skirts, and a budget amount 'X', determine the total number of valid combinations that can be purchased such t...read more

Ans.

Determine total number of valid shopping combinations within budget

  • Iterate through all possible combinations of items from each array

  • Check if the total cost of the combination is within the budget

  • Return the count of valid combinations

Q6. Find All Pairs Adding Up to Target

Given an array of integers ARR of length N and an integer Target, your task is to return all pairs of elements such that they add up to the Target.

Input:

The first line conta...read more
Ans.

Find all pairs of elements in an array that add up to a given target.

  • Iterate through the array and use a hashmap to store the difference between the target and each element.

  • Check if the current element exists in the hashmap, if so, print the pair.

  • If no pair is found, print (-1, -1).

Frequently asked in,

Share interview questions and help millions of jobseekers 🌟

man-with-laptop

Q7. Sum of Even & Odd Digits

You need to determine the sum of even digits and odd digits separately from a given integer.

Input:

The first line of input is an integer T representing the number of test cases. Each t...read more

Ans.

Given an integer, find the sum of even and odd digits separately.

  • Iterate through each digit of the integer and check if it is even or odd

  • Keep track of the sum of even and odd digits separately

  • Return the sums of even and odd digits

Q8. Maximum Depth of a Binary Tree Problem Statement

Given the root node of a binary tree with N nodes, where each node contains integer values, determine the maximum depth of the tree. The depth is defined as the ...read more

Ans.

Find the maximum depth of a binary tree given its level order traversal.

  • Traverse the tree level by level and keep track of the depth using a queue data structure.

  • For each level, increment the depth by 1 until all nodes are processed.

  • Return the maximum depth encountered during traversal as the final result.

  • Example: For input [5, 10, 15, 20, -1, 25, 30, -1, 40, -1, -1, -1, -1, 45], the maximum depth is 7.

SDE-2 Jobs

SDE-2 (UI) (Frontend) 2-5 years
Simplilearn
3.2
Bangalore / Bengaluru

Q9. Sliding Window Maximum Problem Statement

You are given an array/list of integers with length 'N'. A sliding window of size 'K' moves from the start to the end of the array. For each of the 'N'-'K'+1 possible wi...read more

Ans.

Sliding window maximum problem where we find maximum element in each window of size K.

  • Use a deque to store indices of elements in decreasing order within the window.

  • Pop elements from the deque that are out of the current window.

  • Add the maximum element to the result for each window.

Q10. Reverse Linked List Problem Statement

Given a Singly Linked List of integers, your task is to reverse the Linked List by altering the links between the nodes.

Input:

The first line of input is an integer T, rep...read more
Ans.

Reverse a singly linked list by altering the links between nodes.

  • Iterate through the linked list and reverse the links between nodes

  • Use three pointers to keep track of the current, previous, and next nodes

  • Update the links between nodes to reverse the list

  • Return the head of the reversed linked list

Q11. Max Submatrix Problem Statement

You are provided with a matrix MAT consisting of integers, with dimensions N x M (i.e., N rows and M columns). Your objective is to determine the maximum sum submatrix within thi...read more

Ans.

Find the maximum sum submatrix in a given matrix.

  • Iterate over all possible submatrices and calculate their sums

  • Use Kadane's algorithm to find the maximum sum subarray in each row

  • Combine the sums of rows to find the maximum sum submatrix

Q12. Maximum Number With Single Swap

You are given an array of N elements that represent the digits of a number. You can perform one swap operation to exchange the values at any two indices. Your task is to determin...read more

Ans.

Given an array of digits, find the maximum number that can be achieved by performing at most one swap.

  • Iterate through the array to find the maximum digit.

  • If the maximum digit is already at the beginning, find the next maximum digit and swap them.

  • If the maximum digit is not at the beginning, swap it with the digit at the beginning.

Q13. Median in a Stream Problem Statement

Your task is to determine the median of integers as they are read from a data stream. The median is the middle value in the ordered list of numbers. If the list length is ev...read more

Ans.

Find median of integers in a data stream as they are read.

  • Use two heaps - max heap for lower half of numbers and min heap for upper half.

  • Keep the size of two heaps balanced to find the median efficiently.

  • Handle even and odd number of elements separately to calculate median.

  • Return vector of medians after each element is read from the stream.

Q14. Triplets with Given Sum Problem

Given an array or list ARR consisting of N integers, your task is to identify all distinct triplets within the array that sum up to a specified number K.

Explanation:

A triplet i...read more

Ans.

The task is to find all distinct triplets in an array that sum up to a specified number.

  • Iterate through all possible triplets using three nested loops.

  • Check if the sum of the triplet equals the target sum.

  • Print the triplet if found, else print -1.

Frequently asked in,

Q15. Equilibrium Index Problem Statement

Given an array Arr consisting of N integers, your task is to find the equilibrium index of the array.

An index is considered as an equilibrium index if the sum of elements of...read more

Ans.

Find the equilibrium index of an array where sum of elements on left equals sum on right.

  • Iterate through the array and calculate prefix sum and suffix sum at each index.

  • Compare prefix sum and suffix sum to find equilibrium index.

  • Return the left-most equilibrium index found.

Q16. String Transformation Problem

Given a string (STR) of length N, you are tasked to create a new string through the following method:

Select the smallest character from the first K characters of STR, remove it fr...read more

Ans.

Given a string, select smallest character from first K characters, remove it, and append to new string until original string is empty.

  • Iterate through the string, selecting the smallest character from the first K characters each time.

  • Remove the selected character from the original string and append it to the new string.

  • Repeat the process until the original string is empty.

  • Return the final new string formed after the operations.

Q17. The Ninja Port Problem

Ninja is in a city with 'N' colonies, where each colony contains 'K' houses. He starts at house number "sourceHouse" in colony number "sourceColony" and wants to reach house number "desti...read more

Ans.

The Ninja Port Problem involves finding the minimum time for a ninja to travel between colonies and houses using secret paths and teleportation.

  • Calculate the minimum time considering teleportation within colonies, traveling between colonies, and secret paths.

  • Keep track of the number of secret paths used and ensure they are one-way.

  • Consider the constraints provided to optimize the solution.

  • Example: N=2, K=3, S=1, P=1, sourceHouse=1, sourceColony=1, destinationHouse=3, destinat...read more

Q18. Add Two Numbers Represented by Linked Lists

Your task is to find the sum list of two numbers represented by linked lists and return the head of the sum list.

Explanation:

The sum list should be a linked list re...read more

Ans.

Add two numbers represented by linked lists and return the head of the sum list.

  • Traverse both linked lists simultaneously while keeping track of carry from previous sum

  • Create a new linked list to store the sum of the two numbers

  • Handle cases where one linked list is longer than the other by padding with zeros

  • Update the sum and carry values accordingly while iterating through the linked lists

Q19. Clone a Binary Tree with Random Pointers

Given a binary tree where each node has pointers to its left, right, and a random node, create a deep copy of the binary tree.

Input:

The first line contains an integer ...read more
Ans.

Clone a binary tree with random pointers and verify if cloning was successful by printing inorder traversal.

  • Create a deep copy of the binary tree with random pointers.

  • Print the inorder traversal of the cloned binary tree.

  • Verify cloning success by printing '1' if successful, '0' otherwise.

Q20. Course Schedule II Problem Statement

You are provided with a number of courses 'N', some of which have prerequisites. There is a matrix named 'PREREQUISITES' of size 'M' x 2. This matrix indicates that for ever...read more

Ans.

Given courses with prerequisites, determine a valid order to complete all courses.

  • Create a graph with courses as nodes and prerequisites as edges.

  • Use topological sorting to find a valid order to complete all courses.

  • Return an empty list if it's impossible to complete all courses.

Q21. Group Anagrams Together

Given an array/list of strings STR_LIST, group the anagrams together and return each group as a list of strings. Each group must contain strings that are anagrams of each other.

Example:...read more

Ans.

Group anagrams together in a list of strings.

  • Iterate through the list of strings and sort each string to group anagrams together.

  • Use a hashmap to store the sorted string as key and the original string as value.

  • Return the values of the hashmap as the grouped anagrams.

Q22. Maximum Product Subarray Problem Statement

Given an array of integers, determine the contiguous subarray that produces the maximum product of its elements.

Explanation:

A subarray can be derived from the origin...read more

Ans.

Find the maximum product of a contiguous subarray in an array of integers.

  • Iterate through the array and keep track of the maximum and minimum product ending at each index.

  • Update the maximum product by considering the current element, the maximum product ending at the previous index multiplied by the current element, and the minimum product ending at the previous index multiplied by the current element.

  • Update the minimum product similarly.

  • Return the maximum product found durin...read more

Q23. Maximum Sum Rectangle Problem

Given an M x N matrix of integers ARR, your task is to identify the rectangle within the matrix that has the greatest sum of its elements.

Input:

The first line of input contains a...read more
Ans.

The task is to find the rectangle within a matrix that has the greatest sum of its elements.

  • Iterate through all possible rectangles within the matrix

  • Calculate the sum of each rectangle and keep track of the maximum sum

  • Return the maximum sum obtained from any rectangle within the matrix

Q24. Validate Binary Search Tree (BST)

You are given a binary tree with 'N' integer nodes. Your task is to determine whether this binary tree is a Binary Search Tree (BST).

BST Definition:

A Binary Search Tree (BST)...read more

Ans.

Validate if a given binary tree is a Binary Search Tree (BST) or not.

  • Check if the left subtree of a node contains only nodes with data less than the node's data

  • Check if the right subtree of a node contains only nodes with data greater than the node's data

  • Recursively check if both left and right subtrees are also binary search trees

Q25. Prime Time Again Problem Statement

You are given two integers DAY_HOURS and PARTS. The integer 'DAY_HOURS' represents the number of hours in a day, and the day can be divided into 'PARTS' equal parts. Your task...read more

Ans.

Find total instances of equivalent prime groups in a day divided into equal parts.

  • Iterate through each part of the day and check for prime pairs in different parts

  • Use a helper function to check if a number is prime

  • Ensure the day is evenly divided by parts and each prime group has hours from different parts

Q26. Edit Distance Problem Statement

Given two strings S and T with lengths N and M respectively, your task is to find the "Edit Distance" between these strings.

The Edit Distance is defined as the minimum number of...read more

Ans.

The task is to find the minimum number of operations required to convert one string into another using delete, replace, and insert operations.

  • Use dynamic programming to solve the problem efficiently.

  • Create a 2D array to store the minimum edit distance for substrings of the two input strings.

  • Iterate through the strings and update the array based on the operations needed for each character.

  • Return the value in the bottom right corner of the array as the minimum edit distance.

Q27. Distance Between Two Nodes in a Binary Tree

Given a binary tree and the values of two distinct nodes, determine the distance between these two nodes in the tree. The distance is defined as the minimum number of...read more

Ans.

Calculate the distance between two nodes in a binary tree.

  • Traverse the tree to find the paths from the root to each node

  • Find the lowest common ancestor of the two nodes

  • Calculate the distance by summing the distances from each node to the common ancestor

Q28. Minimum Operations Problem Statement

You are given an array 'ARR' of size 'N' consisting of positive integers. Your task is to determine the minimum number of operations required to make all elements in the arr...read more

Ans.

Minimum number of operations to make all elements in the array equal by performing addition, subtraction, multiplication, or division.

  • Iterate through the array to find the maximum and minimum values.

  • Calculate the difference between the maximum and minimum values.

  • The minimum number of operations needed is the difference between the maximum and minimum values.

Q29. Subarray With Given Sum Problem Statement

Given an array ARR of N integers and an integer S, determine if there exists a contiguous subarray within the array with a sum equal to S. If such a subarray exists, re...read more

Ans.

Given an array of integers, find a subarray with a given sum S.

  • Use a sliding window approach to find the subarray with the given sum.

  • Keep track of the current sum and adjust the window based on the sum.

  • Return the start and end indices of the subarray if found, otherwise return [-1, -1].

Q30. Find the Duplicate Number Problem Statement

Given an integer array 'ARR' of size 'N' containing numbers from 0 to (N - 2). Each number appears at least once, and there is one number that appears twice. Your tas...read more

Ans.

Find the duplicate number in an array of integers from 0 to (N-2).

  • Iterate through the array and keep track of the frequency of each number using a hashmap.

  • Return the number with a frequency greater than 1 as the duplicate number.

Q31. How can you prevent the breaking of the singleton pattern using reflections?
Ans.

Prevent breaking singleton pattern using reflections by throwing an exception in the private constructor.

  • Throw an exception in the private constructor if an instance already exists.

  • Use a flag to track if an instance has been created and throw an exception if an attempt is made to create another instance.

  • Use enums to create a singleton to prevent reflection attacks.

Q32. Can you explain the concepts of Object-Oriented Programming (OOP) with real-life examples?
Ans.

OOP is a programming paradigm based on the concept of objects, which can contain data and code to manipulate that data.

  • OOP focuses on creating objects that interact with each other to solve complex problems.

  • Encapsulation: Objects can hide their internal state and require interactions through well-defined interfaces. Example: A car object with methods like start(), stop(), accelerate().

  • Inheritance: Objects can inherit attributes and methods from parent objects. Example: Animal...read more

Q33. Can you explain the ACID properties in the context of database management systems?
Ans.

ACID properties are essential characteristics of a transaction in a database management system.

  • Atomicity ensures that either all operations in a transaction are completed successfully or none of them are.

  • Consistency ensures that the database remains in a valid state before and after the transaction.

  • Isolation ensures that the execution of multiple transactions concurrently does not interfere with each other.

  • Durability ensures that once a transaction is committed, its effects a...read more

Q34. Can you explain the concept of normalization and its types?
Ans.

Normalization is the process of organizing data in a database to reduce redundancy and improve data integrity.

  • Normalization is used to eliminate data redundancy and ensure data integrity in a database.

  • There are different normal forms such as 1NF, 2NF, 3NF, BCNF, and 4NF.

  • Each normal form has specific rules that must be followed to ensure data is properly organized.

  • Normalization helps in reducing data anomalies and inconsistencies in a database.

  • Example: Splitting a table into m...read more

Q35. Design an LRU (Least Recently Used) cache.
Ans.

Design an LRU cache to store and retrieve data based on least recently used policy.

  • Use a doubly linked list to keep track of the order of usage of the cache entries.

  • Maintain a hash map to quickly access the cache entries based on their keys.

  • When a new entry is accessed, move it to the front of the linked list to mark it as the most recently used.

  • If the cache is full, remove the least recently used entry from the end of the linked list.

  • Implement methods like get(key) and put(k...read more

Q36. Design an application similar to Practo.
Ans.

An application similar to Practo for booking doctor appointments and managing medical records.

  • Allow users to search for doctors based on specialty, location, and availability.

  • Provide a platform for users to book appointments online with their preferred doctors.

  • Include features for users to store and access their medical records securely.

  • Implement a rating and review system for doctors to help users make informed decisions.

  • Offer teleconsultation services for remote medical con...read more

Q37. Design a live video broadcast platform.
Ans.

Design a live video broadcast platform.

  • Implement video streaming functionality using protocols like RTMP or WebRTC

  • Include features for live chat, reactions, and audience engagement

  • Ensure scalability and reliability by using cloud services like AWS or Azure

  • Provide analytics for viewership data and user engagement

  • Integrate monetization options such as ads or subscriptions

Q38. Indexing in database and SQL vs NO SQL

Ans.

Indexing is important for efficient data retrieval. SQL databases use traditional indexing while NoSQL databases use various indexing techniques.

  • SQL databases use B-tree indexing while NoSQL databases use hash-based, inverted index, or full-text search indexing

  • SQL databases are better suited for structured data while NoSQL databases are better suited for unstructured or semi-structured data

  • SQL databases have strict schema requirements while NoSQL databases are schema-less

  • Exam...read more

Q39. Connection pooling in databases

Ans.

Connection pooling is a technique used to improve performance and scalability of database applications.

  • Connection pooling allows multiple clients to reuse a single database connection, reducing the overhead of creating and tearing down connections.

  • It helps in improving the performance of the application by reducing the time taken to establish a new connection.

  • Connection pooling can be implemented at the application level or at the database level.

  • Examples of connection pooling...read more

Q40. Event loop in javascript

Ans.

Event loop is a mechanism in JavaScript that allows asynchronous code to be executed.

  • Event loop continuously checks the call stack and the task queue.

  • If the call stack is empty, it takes the first task from the queue and pushes it to the call stack.

  • If the task is an asynchronous operation, it is pushed to the Web API and a callback function is registered.

  • Once the operation is complete, the callback function is pushed to the task queue.

  • The event loop then takes the callback fu...read more

Interview Tips & Stories
Ace your next interview with expert advice and inspiring stories

Interview experiences of popular companies

3.7
 • 10.4k Interviews
4.1
 • 5k Interviews
4.0
 • 1.3k Interviews
3.8
 • 386 Interviews
3.9
 • 207 Interviews
3.4
 • 139 Interviews
3.5
 • 77 Interviews
3.6
 • 77 Interviews
View all

Calculate your in-hand salary

Confused about how your in-hand salary is calculated? Enter your annual salary (CTC) and get your in-hand salary

SDE-2 Interview Questions
Share an Interview
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter