Software Engineer
7000+ Software Engineer Interview Questions and Answers
Q1. Bridge and torch problem : Four people come to a river in the night. There is a narrow bridge, but it can only hold two people at a time. They have one torch and, because it's night, the torch has to be used wh...
read moreFour people with different crossing times need to cross a bridge with a torch. Only two can cross at a time. What is the least time taken?
Person A and B cross first, taking 2 minutes
A goes back with the torch, taking 1 minute
C and D cross together, taking 10 minutes
B goes back with the torch, taking 2 minutes
A and B cross together, taking 2 minutes
Total time taken is 17 minutes
Q2. In a dark room,there is a box of 18 white and 5 black gloves. You are allowed to pick one and then you are allowed to keep it and check it outside. How many turns do you need to take in order for you to find a...
read moreYou need to take 36 turns to find a perfect pair.
You need to pick 19 gloves to ensure a perfect pair.
The worst case scenario is picking 18 white gloves and then the 19th glove is black.
In that case, you need to pick 17 more gloves to find a black one and complete the pair.
Software Engineer Interview Questions and Answers for Freshers
Q3. 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
Given an array of size N containing numbers from 0 to (N-2), find and return the duplicate number.
Iterate through the array and keep track of the frequency of each number using a hashmap.
Return the number with a frequency of 2.
Q4. Tell me something about yourself. Define encapsulation. What is inheritance. What is constructor. What is method overloading. Can we overload a constructor. What is overriding. Difference between overloading an...
read moreThe interview questions cover topics like encapsulation, inheritance, constructors, method overloading, overriding, exception handling, and hobbies.
Encapsulation is the process of hiding the internal details of an object and providing access through methods.
Inheritance is a mechanism in which one class inherits the properties and behaviors of another class.
A constructor is a special method used to initialize objects.
Method overloading is the ability to define multiple methods...read more
Q5. Puzzle : 100 people are standing in a circle .each one is allowed to shoot a person infront of him and he hands the gun to the next to next person for e.g 1st person kills 2nd and hands gun to 3rd .This continu...
read moreA puzzle where 100 people shoot the person in front of them until only one person remains.
Each person shoots the person in front of them and hands the gun to the next to next person.
This continues until only one person remains.
The last person standing is the one who was not shot by anyone.
Q6. How can you cut a rectangular cake in 8 symmetric pieces in three cuts?
Cut the cake in half horizontally, then vertically, and finally cut each half diagonally.
Cut the cake horizontally through the middle.
Cut the cake vertically through the middle.
Cut each half diagonally from corner to corner.
Ensure each cut is made symmetrically to get 8 equal pieces.
Example: https://www.youtube.com/watch?v=ZdGmuCJzQFo
Share interview questions and help millions of jobseekers 🌟
Q7. What is the difference between a stack and a queue? Give an example where you would use each.
A stack is a LIFO data structure while a queue is a FIFO data structure.
Stack: Last In First Out (LIFO), used in undo/redo functionality, backtracking, and recursion.
Queue: First In First Out (FIFO), used in job scheduling, breadth-first search, and printing.
Stack uses push() and pop() operations while queue uses enqueue() and dequeue() operations.
Q8. Split Binary String Problem Statement
Chintu has a long binary string str
. A binary string is a string that contains only 0 and 1. He considers a string to be 'beautiful' if and only if the number of 0's and 1'...read more
The task is to split a binary string into beautiful substrings with equal number of 0's and 1's.
Count the number of 0's and 1's in the string.
Iterate through the string and split it into beautiful substrings whenever the count of 0's and 1's becomes equal.
Return the maximum number of beautiful substrings that can be formed.
If it is not possible to split the string into beautiful substrings, return -1.
Software Engineer Jobs
Q9. N-th Fibonacci Number Problem Statement
Given an integer ‘N’, your task is to find and return the N’th Fibonacci number using matrix exponentiation.
Since the answer can be very large, return the answer modulo ...read more
The task is to find the Nth Fibonacci number using matrix exponentiation and return the answer modulo 10^9 + 7.
Implement a function to find the Nth Fibonacci number using matrix exponentiation.
Return the answer modulo 10^9 + 7 to handle large values.
Use the formula F(n) = F(n-1) + F(n-2) with initial values F(1) = F(2) = 1.
Optimize the solution to achieve better than O(N) time complexity.
Consider solving the problem using dynamic programming or matrix exponentiation technique...read more
Q10. Reverse String Operations Problem Statement
You are provided with a string S
and an array of integers A
of size M
. Your task is to perform M
operations on the string as specified by the indices in array A
.
The ...read more
Given a string and an array of indices, reverse substrings based on the indices to obtain the final string.
Iterate through the array of indices and reverse the substrings accordingly
Ensure the range specified by each index is non-empty
Return the final string after all operations are completed
Q11. Find the Second Largest Element
Given an array or list of integers 'ARR', identify the second largest element in 'ARR'.
If a second largest element does not exist, return -1.
Example:
Input:
ARR = [2, 4, 5, 6, ...read more
The task is to find the second largest element in an array of integers.
Iterate through the array and keep track of the largest and second largest elements.
Initialize the largest and second largest variables with the first two elements of the array.
Compare each element with the largest and second largest variables and update them accordingly.
Return the second largest element at the end.
Handle the case where no second largest element exists.
Q12. Factorial Calculation Problem
Given an integer N
, calculate and print the factorial of N
. The factorial of a number N
is defined as the product of all positive integers up to N
.
Example:
Input:
N = 4
Output:
24...read more
Calculate and print the factorial of a given integer N.
Iterate from 1 to N and multiply each number to calculate factorial.
Handle edge cases like N=0 or N=1 separately.
Use recursion to calculate factorial efficiently.
Consider using dynamic programming to optimize factorial calculation.
Ensure to handle large values of N to prevent overflow issues.
Q13. What is the reason that the Iterative Waterfall model was introduced?
Iterative Waterfall model was introduced to address the limitations of the traditional Waterfall model.
Iterative Waterfall model allows for feedback and changes during the development process.
It breaks down the development process into smaller, more manageable stages.
It reduces the risk of project failure by identifying and addressing issues early on.
It allows for better collaboration between developers and stakeholders.
Examples include Rational Unified Process (RUP) and Agil...read more
Q14. Knapsack Problem Statement
There is a potter with a limited amount of pottery clay (denoted as 'K' units) who can make 'N' different items. Each item requires a specific amount of clay and yields a certain prof...read more
The Knapsack Problem involves maximizing profit by choosing which items to make with limited resources.
Understand the problem statement and constraints provided.
Implement a dynamic programming solution to solve the Knapsack Problem efficiently.
Iterate through the items and clay units to calculate the maximum profit that can be achieved.
Consider both the clay requirement and profit of each item while making decisions.
Ensure the solution runs within the given time limit of 1 se...read more
Q15. Nth Element Of Modified Fibonacci Series
Given two integers X
and Y
as the first two numbers of a series, and an integer N
, determine the Nth element of the series following the Fibonacci rule: f(x) = f(x - 1) ...read more
Calculate the Nth element of a modified Fibonacci series given the first two numbers and N, with the result modulo 10^9 + 7.
Implement a function to calculate the Nth element of the series using the Fibonacci rule f(x) = f(x - 1) + f(x - 2)
Return the answer modulo 10^9 + 7 due to the possibility of a very large result
The series starts with the first two numbers X and Y, and the position N in the series
Q16. Split the String Problem Statement
You are given a string str
consisting of N
lowercase alphabets. Your task is to determine if it is possible to divide the string into three non-empty substrings such that one ...read more
Determine if it is possible to divide a string into three non-empty substrings where one is a substring of the other two.
Check if any substring of the string is a substring of the other two substrings.
Iterate through all possible divisions of the string into three non-empty substrings.
Use two pointers to find all possible substrings efficiently.
Q17. City of Happy People Problem Statement
Imagine a city where the happiness of each resident is described by a numerical value. Ninja, who is visiting this city, is interested in forming groups of people such tha...read more
The problem is to find the number of ways to form a group of people such that the overall happiness of the group falls within a given range.
Iterate through all possible subsets of the given array/list
Calculate the sum of happiness values for each subset
Count the number of subsets whose sum falls within the given range
Q18. 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
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 current element.
Check if the current element exists in the hashmap, if so, print the pair.
If no pair is found, print (-1, -1).
Q19. One question of sorting for a list of people belonging to different cities and states.
Sort a list of people by their cities and states.
Use a sorting algorithm like quicksort or mergesort.
Create a custom comparator function that compares the city and state of each person.
If two people belong to the same city and state, sort them by their names.
Example: [{name: 'John', city: 'New York', state: 'NY'}, {name: 'Jane', city: 'Boston', state: 'MA'}]
Example output: [{name: 'Jane', city: 'Boston', state: 'MA'}, {name: 'John', city: 'New York', state: 'NY'}]
Q20. Can you describe a challenging technical problem you faced and how you solve it ?
Developing a real-time chat application with high scalability and low latency.
Designing a distributed architecture to handle a large number of concurrent users.
Implementing efficient data synchronization between multiple servers.
Optimizing network communication to minimize latency.
Ensuring data consistency and reliability in a distributed environment.
Q21. 2 queues q1 and q2 are given.A background process copies elements from q1 to q2.In case an error occurs elements from q2 need to be copied back again to q1.Write this error handling function using foll function...
read moreThe error handling function copies elements from q2 back to q1 in case of an error.
Use q_len() to get the length of the queues
Use q_insert() and q_remove() to manipulate the queues
Iterate through q2 and use q_insert() to copy elements back to q1
Q22. Sum of Two Numbers Represented as Arrays
Given two numbers in the form of two arrays where each element of the array represents a digit, calculate the sum of these two numbers and return this sum as an array.
E...read more
Given two numbers represented as arrays, calculate their sum and return the result as an array.
Iterate through the arrays from right to left, adding digits and carrying over if necessary
Handle cases where one array is longer than the other by considering the remaining digits
Ensure the final sum array does not have any leading zeros
Q23. Reverse a Number Problem Statement
Create a program to reverse a given integer N
. The output should be the reversed integer.
Note:
If a number has trailing zeros, their reversed version should not include them....read more
Reverse a given integer while excluding trailing zeros.
Create a program to reverse the given integer by converting it to a string and then reversing it.
Remove any trailing zeros from the reversed string before converting it back to an integer.
Handle the constraints of the input integer being between 0 and 10^8.
Example: For input 1230, the output should be 321.
Q24. String Compression Problem Statement
Ninja needs to perform basic string compression. For any character that repeats consecutively more than once, replace the repeated sequence with the character followed by th...read more
Implement a function to compress a string by replacing consecutive characters with the character followed by the count of repetitions.
Iterate through the input string and keep track of consecutive characters and their counts
Replace consecutive characters with the character followed by the count of repetitions if count is greater than 1
Return the compressed string
Q25. Set Matrix Zeros Problem Statement
Given an N x M
integer matrix, if an element is 0, set its entire row and column to 0's, and return the matrix. Specifically, if a cell has a value 0 (i.e., matrix[i][j] == 0
)...read more
To solve the Set Matrix Zeros problem, we can use O(1) space by utilizing the first row and column to store information about zeros in the rest of the matrix.
Iterate through the matrix and use the first row and column to mark rows and columns that need to be zeroed out.
After marking, iterate through the matrix again and zero out the rows and columns based on the marks in the first row and column.
Remember to handle the special case of the first row and column separately.
Exampl...read more
Q26. Spiral Matrix Path Problem
You are provided with a two-dimensional array named MATRIX
of size N x M, consisting of integers. Your task is to return the elements of the matrix following a spiral order.
Input:
Th...read more
Implement a function to return elements of a matrix in spiral order.
Iterate through the matrix in a spiral order by adjusting boundaries as you move along.
Keep track of the direction of movement (right, down, left, up) to traverse the matrix correctly.
Handle edge cases like when the matrix is a single row or column separately.
Q27. what are the differences between stored procedure and triggers in SQL?
Stored procedures are precompiled SQL statements that can be executed on demand, while triggers are automatically executed in response to specific events.
Stored procedures are explicitly called by the user, while triggers are automatically invoked by the database system.
Stored procedures can accept parameters and return values, while triggers cannot.
Stored procedures can be executed independently, while triggers are always associated with a specific table or view.
Stored proce...read more
Q28. Maximum Sum After Removing K Corner Elements
Given an array arr
of 'N' integer elements, your goal is to remove 'K' elements from either the beginning or the end of the array. The task is to return the maximum ...read more
Given an array of integers, remove K elements from either end to maximize sum of remaining elements.
Iterate through all possible combinations of removing K elements from start and end
Calculate sum of remaining elements for each combination
Return the maximum sum obtained
Q29. Maximum Sum Subarray Problem Statement
Given an array of integers, find the maximum sum of any contiguous subarray within the array.
Example:
Input:
array = [34, -50, 42, 14, -5, 86]
Output:
137
Explanation:
Th...read more
Find the maximum sum of any contiguous subarray within an array in O(N) time complexity.
Use Kadane's algorithm to find the maximum sum subarray in O(N) time complexity
Initialize max_sum and current_sum to the first element of the array
Iterate through the array, updating current_sum and max_sum as needed
Return max_sum as the maximum sum of any contiguous subarray
Q30. What are seven layers of networking?
The seven layers of networking refer to the OSI model which defines how data is transmitted over a network.
The seven layers are: Physical, Data Link, Network, Transport, Session, Presentation, and Application.
Each layer has a specific function and communicates with the layers above and below it.
For example, the Physical layer deals with the physical transmission of data, while the Application layer deals with user interfaces and applications.
Understanding the OSI model is imp...read more
Q31. Reverse Linked List Problem Statement
Given a singly linked list of integers, return the head of the reversed linked list.
Example:
Initial linked list: 1 -> 2 -> 3 -> 4 -> NULL
Reversed linked list: 4 -> 3 -> 2...read more
Reverse a singly linked list of integers and return the head of the reversed linked list.
Iterate through the linked list and reverse the pointers to point to the previous node instead of the next node.
Use three pointers to keep track of the current, previous, and next nodes while reversing the linked list.
Update the head of the reversed linked list as the last node encountered during the reversal process.
Q32. Generate Binary Strings with No Consecutive 1s
Given an integer K
, your task is to produce all binary strings of length 'K' that do not contain consecutive '1's.
Input:
The input begins with an integer 'T', the...read more
Generate all binary strings of length 'K' with no consecutive '1's in lexicographically increasing order.
Use backtracking to generate all possible binary strings without consecutive '1's.
Start with an empty string and recursively add '0' or '1' based on the condition.
Keep track of the current string and its length to ensure no consecutive '1's are added.
Sort the generated strings in lexicographically increasing order before outputting.
Q33. Merge Two Sorted Linked Lists Problem Statement
You are provided with two sorted linked lists. Your task is to merge them into a single sorted linked list and return the head of the combined linked list.
Input:...read more
Merge two sorted linked lists into a single sorted linked list with constant space complexity and linear time complexity.
Create a dummy node to start the merged list
Compare the values of the two linked lists and append the smaller value to the merged list
Move the pointer of the merged list and the pointer of the smaller value's linked list
Continue this process until one of the linked lists is fully traversed
Append the remaining elements of the other linked list to the merged ...read more
Q34. Matrix Transformation Problem Statement
Given a 2-dimensional matrix of size NxN containing 0s and 1s, the task is to modify the matrix such that, if an element is 1, set its entire row and column to 1. In the ...read more
Modify a matrix by setting entire row and column to 1 if an element is 1, then count the number of 1s.
Iterate through the matrix to find elements with value 1
Use two arrays to keep track of rows and columns to be modified
Update the matrix by setting entire row and column to 1 if an element is 1
Count the number of 1s in the modified matrix
Q35. Sum of Two Elements Equals the Third
Determine if a given array contains a valid triplet of integers where two elements sum up to the third. Specifically, find indices i, j, and k such that i != j
, j != k
, and ...read more
Check if a given array contains a valid triplet where two elements sum up to the third.
Iterate through all possible triplets in the array and check if any of the conditions are satisfied.
Use nested loops to compare each element with every other element in the array.
Handle cases where the elements are not distinct by ensuring i != j, j != k, and i != k.
Q36. Given an array A[n], write a C program to find P and Q (P>Q) such that A[P] - A[Q] is maximum
C program to find P and Q (P>Q) such that A[P] - A[Q] is maximum
Iterate through array and keep track of maximum difference and corresponding indices
Initialize P and Q to first two elements and update as necessary
Time complexity: O(n)
Q37. Loot Houses Problem Statement
A thief is planning to steal from several houses along a street. Each house has a certain amount of money stashed. However, the thief cannot loot two adjacent houses. Determine the...read more
Determine the maximum amount of money a thief can steal from houses without looting two consecutive houses.
Create an array 'dp' to store the maximum money that can be stolen up to the i-th house.
Iterate through the houses and update 'dp' based on whether the current house is stolen or not.
Return the maximum value in 'dp' as the answer.
Example: For input N=4 and values=[6, 7, 1, 30], the output should be 36.
Q38. Merge Overlapping Intervals Problem Statement
Given a specified number of intervals, where each interval is represented by two integers denoting its boundaries, the task is to merge all overlapping intervals an...read more
Merge overlapping intervals and return sorted list of merged intervals.
Identify overlapping intervals based on start and end times
Merge overlapping intervals to form new intervals
Sort the merged intervals in ascending order of start times
Q39. Wildcard Pattern Matching Problem Statement
Implement a wildcard pattern matching algorithm to determine if a given wildcard pattern matches a text string completely.
The wildcard pattern may include the charac...read more
The task is to implement a wildcard pattern matching algorithm that checks if a given wildcard pattern matches a given text.
The wildcard pattern can include the characters '?' and '*'
'?' matches any single character
'*' matches any sequence of characters (sequence can be of length 0 or more)
The matching should cover the entire text, not partial text
Implement a function that takes the wildcard pattern and the text as input and returns True if the text matches the pattern, False...read more
Q40. Idempotent Matrix Verification
Determine if a given N * N matrix is an idempotent matrix. A matrix is considered idempotent if it satisfies the following condition:
M * M = M
Input:
The first line contains a si...read more
Check if a given matrix is idempotent by verifying if M * M equals M.
Calculate the product of the matrix with itself and compare it with the original matrix.
If the product equals the original matrix, then it is idempotent.
Iterate through the matrix elements to perform the necessary calculations.
Q41. If there are 200 fishes in an aquarium. 99% are red. How many fishes have to be removed to make the red fishes 98 % in the aquarium?
To make the red fishes 98%, 50 fishes have to be removed from the aquarium.
Calculate 1% of 200 fishes to find out how many fishes represent 1%.
Multiply the result by 2 to find out how many fishes represent 2%.
Subtract the result from 200 to find out how many fishes represent 98%.
Q42. Best Time to Buy and Sell Stock Problem Statement
Given an array prices
representing the prices of a stock where each element indicates the price at a given minute, determine the maximum profit you can achieve ...read more
Find the maximum profit by buying and selling a stock once based on given prices.
Iterate through the prices array and keep track of the minimum price seen so far and the maximum profit achievable.
Calculate the profit by subtracting the current price from the minimum price and update the maximum profit if needed.
Return the maximum profit, ensuring it is not negative.
Example: prices = [2, 100, 150, 120], Buy at 2, sell at 150, profit = 150 - 2 = 148.
Q43. Common Elements Between Array of Strings Problem Statement
Given two 1-dimensional arrays containing strings of lowercase alphabets, determine and return the elements that are common in both arrays, i.e., the s...read more
Given two arrays of strings, find and return the common elements in the order they appear in the second array.
Iterate through the strings in the second array and check if they exist in the first array.
Maintain a set to keep track of common elements to avoid duplicates.
Return the common elements as a single space-separated string in the order they appear in the second array.
Count Ways to Reach the Nth Stair
Given a number of stairs, starting from the 0th stair, calculate the number of distinct ways you can reach the Nth stair. You can climb either one step or two steps at a time.
The question is about calculating the number of distinct ways to reach the Nth stair by climbing one or two steps at a time.
Use dynamic programming to solve this problem efficiently.
Define a recursive function to calculate the number of ways to reach each stair.
Consider base cases for 0 and 1 stairs.
Use memoization to store intermediate results and avoid redundant calculations.
Handle large values of N by taking modulo 10^9+7 of the final result.
Example: For N = 3, the number ...read more
Q45. Covid Vaccination Distribution Problem
As the Government ramps up vaccination drives to combat the second wave of Covid-19, you are tasked with helping plan an effective vaccination schedule. Your goal is to ma...read more
Given constraints and rules, maximize vaccines administered on a specific day during a vaccination drive.
Iterate through each test case and calculate the maximum number of vaccines administered on the specified day.
Distribute the available vaccines evenly across the days while adhering to the rules.
Ensure that the sum of vaccines administered does not exceed the maximum allowed.
Maximize the vaccines administered on the specified day to meet the requirements.
Q46. Topological Sort Problem Statement
You are given a directed acyclic graph (DAG). Your task is to perform topological sorting of the graph and return any valid ordering.
Explanation:
A directed acyclic graph is ...read more
Implement a function to perform topological sorting on a directed acyclic graph (DAG) and return any valid ordering.
Create a graph representation using adjacency list or matrix
Perform depth-first search (DFS) to find the topological ordering
Use a stack to keep track of the ordering
Return the ordering as an array of integers
Q47. Consonant Counting Problem Statement
Given a string STR
comprising uppercase and lowercase characters and spaces, your task is to count the number of consonants in the string.
A consonant is defined as an Engli...read more
Count the number of consonants in a given string containing uppercase and lowercase characters and spaces.
Iterate through each character in the string and check if it is a consonant (not a vowel).
Keep a count of the consonants encountered while iterating through the string.
Return the total count of consonants at the end.
Q48. Detect Cycle in Undirected Graph Problem Statement
You are provided with an undirected graph composed of 'N' vertices and 'M' edges, where vertices are labeled from 1 to 'N'.
Your task is to determine if there ...read more
Detect cycle in an undirected graph by checking for a path that begins and ends at the same vertex.
Use Depth First Search (DFS) to traverse the graph and detect cycles.
Maintain a visited set to keep track of visited vertices and a parent pointer to avoid visiting the same vertex twice.
If a visited vertex is encountered that is not the parent of the current vertex, a cycle is detected.
Return 'Yes' if a cycle is found, 'No' otherwise.
Q49. Find Row With Maximum 1's in a Sorted 2D Matrix
You are provided with a 2D matrix containing only the integers 0 or 1. The matrix has dimensions N x M, and each row is sorted in non-decreasing order. Your objec...read more
Find the row with the maximum number of 1's in a sorted 2D matrix.
Iterate through each row of the matrix and count the number of 1's in each row.
Keep track of the row index with the maximum number of 1's seen so far.
Return the index of the row with the maximum number of 1's.
If multiple rows have the same number of 1's, return the row with the smallest index.
Q50. Longest Common Subsequence Problem Statement
Given two strings, S
and T
with respective lengths M
and N
, your task is to determine the length of their longest common subsequence.
A subsequence is a sequence tha...read more
The task is to find the length of the longest common subsequence between two given strings.
Use dynamic programming to solve this problem efficiently.
Create a 2D array to store the lengths of longest common subsequences of substrings.
Iterate through the strings to fill the array and find the length of the longest common subsequence.
Example: For strings 'abcde' and 'ace', the longest common subsequence is 'ace' with length 3.
Interview Questions of Similar Designations
Top Interview Questions for Software Engineer Related Skills
Interview experiences of popular companies
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
Reviews
Interviews
Salaries
Users/Month