SDE-2

filter-iconFilter interviews by

200+ SDE-2 Interview Questions and Answers

Updated 7 Nov 2024

Popular Companies

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. K Most Frequent Words Problem Statement

Given an array of N non-empty words and an integer K, return the K most frequent words sorted by their frequency from highest to lowest.

Example:

Input:
N = 6, K = 2
words...read more
Ans.

Given an array of words and an integer k, return the k most frequent words sorted by frequency.

  • Use a hashmap to count the frequency of each word

  • Use a priority queue to keep track of the k most frequent words

  • Sort the priority queue based on frequency and lexicographical order

SDE-2 Interview Questions and Answers for Freshers

illustration image

Q3. 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

Ans.

Perform a series of reverse string operations on a given string based on specified indices.

  • Iterate through the array of indices and reverse the substring of the string based on the given indices.

  • Ensure to reverse the substring from the starting index to len(S) - starting index - 1.

  • Continue the operations in the sequence specified by the array of indices to get the final string.

Q4. Alien Dictionary Problem Statement

Ninja is mastering an unusual language called the Alien Language. Although it uses the same alphabets as English, the sequence of these alphabets is different. This sequence i...read more

Ans.

The task is to check whether the given words are sorted lexicographically in an alien language.

  • Read the number of test cases

  • For each test case, read the number of words, the words themselves, and the order string

  • Check if the words are sorted lexicographically based on the given order string

  • Print 'YES' if the words are sorted, else print 'NO'

Are these interview questions helpful?

Q5. Make Palindrome Problem Statement

You are provided with a string STR of length N comprising lowercase English alphabet letters. Your task is to determine and return the minimum number of characters that need to...read more

Ans.

The task is to determine the minimum number of characters needed at the beginning of a string to make it a palindrome.

  • Iterate from both ends of the string and compare characters to find the number of characters needed to make it a palindrome.

  • Use dynamic programming to optimize the solution by storing results of subproblems.

  • Handle edge cases like an already palindrome string or an empty string.

  • Example: For 'deed', no characters need to be added, but for 'aabaaca', 2 characters...read more

Q6. 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

Share interview questions and help millions of jobseekers 🌟

man-with-laptop

Q7. Square Root of an Integer Challenge

Given an integer 'A', the objective is to find the largest non-negative integer whose square is less than or equal to 'A'.

The square of a number is defined as the product of...read more

Ans.

Find the largest non-negative integer whose square is less than or equal to a given integer.

  • Use binary search to efficiently find the square root of the given integer.

  • Start with a range from 0 to the given integer and iteratively narrow down the range based on the square of the middle value.

  • Return the largest integer whose square is less than or equal to the given integer.

Q8. Problem: Sort an Array of 0s, 1s, and 2s

Given an array/list ARR consisting of integers where each element is either 0, 1, or 2, your task is to sort this array in increasing order.

Input:

The input starts with...read more
Ans.

The task is to sort an array of 0s, 1s, and 2s in increasing order.

  • Use a three-pointer approach to partition the array into three sections: 0s, 1s, and 2s.

  • Initialize three pointers: low, mid, and high. low points to the start of the array, mid points to the current element being processed, and high points to the end of the array.

  • While mid <= high, if ARR[mid] is 0, swap ARR[low] and ARR[mid], increment low and mid. If ARR[mid] is 1, increment mid. If ARR[mid] is 2, swap ARR[m...read more

SDE-2 Jobs

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

Q9. Find All Pairs with Given Sum

Given an integer array arr and an integer Sum, count and return the total number of pairs in the array whose elements add up to the given Sum.

Input:

The first line contains two sp...read more
Ans.

Count and return the total number of pairs in the array whose elements add up to a given sum.

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

  • Iterate through the array and for each element, check if (Sum - current element) exists in the hashmap.

  • Increment the count of pairs if the complement exists in the hashmap.

Q10. Sum Queries in a Sorted Array

Given two arrays arr and queries, your task is to determine the sum of all elements in arr that are less than or equal to each element in queries. The array arr is provided in sort...read more

Ans.

Find sum of elements in a sorted array less than or equal to each element in queries.

  • Iterate through queries and for each query, find the sum of elements in arr less than or equal to the query element.

  • Use binary search to efficiently find the index of the last element less than or equal to the query element.

  • Keep track of cumulative sum while iterating through arr to avoid recalculating sums.

  • Return the list of sums for each test case.

Q11. Count Ways To Reach The N-th Stair Problem Statement

You are given a number of stairs, N. Starting at the 0th stair, you need to reach the Nth stair. Each time you can either climb one step or two steps. You ha...read more

Ans.

The problem involves finding the number of distinct ways to climb to the Nth stair by taking one or two steps at a time.

  • Use dynamic programming to solve this problem efficiently.

  • The number of ways to reach the Nth stair is the sum of the number of ways to reach the (N-1)th stair and the (N-2)th stair.

  • Handle large inputs by taking modulo 10^9+7 of the result.

  • Example: For N=3, there are 3 ways to climb to the third stair: (0, 1, 2, 3), (0, 2, 3), and (0, 1, 3).

Frequently asked in, ,

Q12. Maximum Subarray Sum Problem Statement

Given an array ARR consisting of N integers, your goal is to determine the maximum possible sum of a non-empty contiguous subarray within this array.

Example of Subarrays:...read more

Ans.

The task is to find the maximum possible sum of a non-empty subarray of an array.

  • Iterate through the array and keep track of the maximum sum encountered so far

  • If the current element is greater than the sum so far, start a new subarray

  • If the current element plus the sum so far is greater than the maximum sum, update the maximum sum

  • Return the maximum sum

Q13. Pair Sum Problem Statement

You are given an integer array 'ARR' of size 'N' and an integer 'S'. Your task is to find and return a list of all pairs of elements where each sum of a pair equals 'S'.

Note:

Each pa...read more

Ans.

Find pairs of elements in an array that sum up to a given value, sorted in a specific order.

  • Sort the array in non-decreasing order.

  • Use two pointers approach to find pairs with sum equal to 'S'.

  • Return pairs in sorted order based on first value, with smaller second value coming first.

Q14. Palindromic Numbers Finder

Given an integer 'N', your task is to identify all palindromic numbers from 1 to 'N'. These are numbers that read the same way forwards and backwards.

Input:

The first line provides a...read more
Ans.

Implement a function to find all palindromic numbers from 1 to N.

  • Iterate from 1 to N and check if each number is a palindrome

  • Use string manipulation to check if a number is a palindrome

  • Consider single-digit numbers as palindromes as well

Q15. Unique Element In Sorted Array

Nobita wants to impress Shizuka by correctly guessing her lucky number. Shizuka provides a sorted list where every number appears twice, except for her lucky number, which appears...read more

Ans.

Find the unique element in a sorted array where all other elements appear twice.

  • Use XOR operation to find the unique element in the sorted array.

  • Iterate through the array and XOR all elements, the result will be the unique element.

  • Time complexity of O(n) can be achieved by iterating through the array once.

Q16. 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,

Q17. Connect Ropes with Minimum Cost

Given 'N' ropes, each having different lengths, your task is to connect these ropes into one single rope. The cost to connect two particular ropes is equal to the sum of their le...read more

Ans.

The task is to connect N ropes into one rope with minimum cost.

  • Sort the array of rope lengths in ascending order.

  • Initialize a variable to keep track of the total cost.

  • While there are more than one rope, take the two shortest ropes and connect them.

  • Add the cost of connecting the two ropes to the total cost.

  • Replace the two shortest ropes with the connected rope.

  • Repeat the above steps until only one rope remains.

  • Return the total cost.

Q18. ...read more

Maximum Path Sum Problem Statement

You are given an n-ary tree consisting of 'N' nodes. Your task is to determine the maximum sum of the path from the root to any leaf node.

Example:

Input:
For the given tree:
Ans.

Find the maximum sum of the path from the root to any leaf node in an n-ary tree.

  • Traverse the tree from root to leaf nodes, keeping track of the sum along the path.

  • At each node, calculate the sum of the path from the root to that node and update the maximum sum found so far.

  • Consider using depth-first search (DFS) to traverse the tree efficiently.

  • Handle cases where nodes are absent (-1) by appropriately updating the path sum.

  • Return the maximum sum found for each test case.

Q19. 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).

Q20. 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

Q21. Boundary Traversal of Binary Tree Problem Statement

Given a binary tree consisting of integers, your task is to provide the boundary nodes of this tree in an anti-clockwise direction, starting with the root nod...read more

Ans.

Boundary traversal of a binary tree to find left boundary, right boundary, and leaf nodes in an anti-clockwise direction.

  • Perform a pre-order traversal to get the left boundary nodes

  • Perform an in-order traversal to get the leaf nodes

  • Perform a post-order traversal to get the right boundary nodes

  • Combine the results in the required order to get the boundary nodes

Q22. ...read more

Diameter of a Binary Tree Problem Statement

Given a binary tree, return the length of its diameter. The diameter of a binary tree is defined as the length of the longest path between any two nodes in the tree.

Ans.

The diameter of a binary tree is the length of the longest path between any two end nodes in the tree.

  • The diameter of a binary tree can be calculated by finding the maximum of the following three values: 1) the diameter of the left subtree, 2) the diameter of the right subtree, and 3) the longest path that passes through the root node.

  • To find the diameter of a binary tree, we can use a recursive approach where we calculate the height of each node and update the diameter at ea...read more

Q23. 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,

Q24. Binary Tree Zigzag Traversal Problem Statement

Given a Binary Tree comprised of 'N' nodes with integer values, your task is to print the zigzag traversal of the tree.

Note:

The zigzag pattern implies that the f...read more

Ans.

Implement a function to print the zigzag traversal of a Binary Tree.

  • Traverse the Binary Tree level by level, alternating the direction of traversal for each level.

  • Use a queue to keep track of nodes at each level and a flag to switch the direction of traversal.

  • Print the values of nodes in the zigzag order as described in the problem statement.

Q25. Maximum Meetings Problem Statement

Given the schedule of N meetings with their start time Start[i] and end time End[i], you need to determine which meetings can be organized in a single meeting room such that t...read more

Ans.

Given N meetings with start and end times, determine which meetings can be organized in a single room to maximize the number of meetings.

  • Sort the meetings based on their end times.

  • Iterate through the sorted meetings and select the first meeting that does not overlap with the previous one.

  • Repeat the process until all meetings are considered.

  • Return the selected meetings in the order they are organized.

Q26. Minimum Count of Balls in a Bag Problem Statement

You are given an integer array ARR of size N, where ARR[i] represents the number of balls in the i-th bag. Additionally, you have an integer M, which indicates ...read more

Ans.

Find the minimum possible value of the maximum number of balls in a bag after performing a given number of operations.

  • Iterate through the bags and split them to minimize the maximum number of balls.

  • Keep track of the maximum number of balls after each operation.

  • Return the minimum possible value of the maximum number of balls.

Q27. Smallest Subarray with K Distinct Elements Problem

Given an array A consisting of N integers, find the smallest subarray of A that contains exactly K distinct integers.

Input:

The first line contains two intege...read more
Ans.

Find the smallest subarray with exactly K distinct integers in an array.

  • Use a sliding window approach to keep track of the subarray with K distinct integers.

  • Use a hashmap to store the frequency of each integer in the current window.

  • Update the window size based on the number of distinct integers found.

  • Keep track of the smallest subarray meeting the criteria.

  • Return the starting and ending indices of the smallest subarray with K distinct integers.

Q28. There is a 12 km road and a contractor who is in-charge of repairing it. Contractor updates you about the work which is done in patches. Like “Road between 3.2 km to 7.9 km repaired ”, “Road between 1.21 km to...

read more
Ans.

Find longest continuous patch on a 12 km road with updates in patches

  • Maintain a variable to keep track of current patch length

  • Update the variable whenever a new patch is added

  • Maintain a variable to keep track of longest patch so far

  • Compare current patch length with longest patch length and update if necessary

  • Use a sorted data structure like a binary search tree to store the patches for efficient search

  • Time complexity: O(nlogn) where n is the number of updates by the contracto...read more

Q29. Minimum Character Deletion Problem Statement

You have been provided a string STR. Your task is to find and return the minimum number of characters that need to be deleted from STR so that each character's frequ...read more

Ans.

Find the minimum number of character deletions needed to make each character's frequency unique in a given string.

  • Iterate through the string and count the frequency of each character.

  • Identify characters with the same frequency and calculate the minimum deletions needed to make them unique.

  • Return the total minimum deletions for each test case.

Q30. 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

Q31. Balanced Parentheses Combinations

Given an integer N representing the number of pairs of parentheses, find all the possible combinations of balanced parentheses using the given number of pairs.

Explanation:

Con...read more

Ans.

Generate all possible combinations of balanced parentheses for a given number of pairs.

  • Use backtracking to generate all valid combinations of balanced parentheses.

  • Keep track of the number of open and close parentheses used in each combination.

  • Recursively build the combinations by adding open parentheses if there are remaining, and then adding close parentheses if the number of open parentheses is greater than the number of close parentheses.

  • Return the list of valid combinatio...read more

Q32. Clone a Linked List with Random Pointers

You are provided with a linked list where each node has two pointers. The first pointer directs to the next node, and the second one, known as the 'random' pointer, can ...read more

Ans.

Clone a linked list with random pointers and return the head of the copied list.

  • Create a deep copy of the linked list by iterating through each node and creating a new node with the same value.

  • Update the random pointers of the new nodes based on the random pointers of the original list.

  • Use a hashmap to keep track of the mapping between original nodes and their corresponding new nodes.

  • Return the head of the copied list.

Q33. Container with Most Water Problem Statement

Given a sequence of 'N' space-separated non-negative integers A[1], A[2], ..., A[i], ..., A[n], where each number in the sequence represents the height of a line draw...read more

Ans.

Find two lines to form a container with maximum water area on a Cartesian plane.

  • Iterate through the array from both ends to find the maximum area.

  • Calculate the area using the formula: (min(height[left], height[right]) * (right - left)).

  • Update the pointers based on the height of the lines to maximize the area.

Q34. Minimum Cost to Reduce Array Problem Statement

You are given an array ARR containing N positive integers. Your task is to reduce the size of this array to 1 by repetitively merging adjacent elements. Each time ...read more

Ans.

Find the minimum cost to reduce an array to a single element by merging adjacent elements with their sum.

  • Iteratively merge adjacent elements to minimize total cost

  • Choose pairs to merge strategically to reduce cost

  • Calculate sum of adjacent elements and update array size

Q35. Number of Subsequences with Even and Odd Sum

Your task is to determine the number of subsequences with odd sums and the number of subsequences with even sums from a given array of positive integers. As resultin...read more

Ans.

Count the number of subsequences with odd and even sums in a given array of positive integers modulo 10^9 + 7.

  • Use dynamic programming to keep track of the count of subsequences with odd and even sums.

  • Consider the parity of each element in the array to determine the count of subsequences with odd and even sums.

  • Apply modulo 10^9 + 7 to handle large resulting numbers.

  • Example: For input [1, 2, 3], there are 3 subsequences with odd sums and 4 subsequences with even sums.

Q36. Sort 0 and 1 Problem Statement

Given an integer array ARR of size N containing only integers 0 and 1, implement a function to sort this array. The solution should scan the array only once without using any addi...read more

Ans.

Sort an array of 0s and 1s in linear time without using additional arrays.

  • Use two pointers approach to swap 0s to the left and 1s to the right.

  • Keep track of the leftmost index of 1s to place 0s before it.

  • Iterate through the array once and swap elements accordingly.

Q37. LRU Cache Implementation Problem

Design and implement a Least Recently Used (LRU) cache data structure. This cache must support the following operations efficiently:

  • get(key): Return the value associated with ...read more
Ans.

Implement a Least Recently Used (LRU) cache data structure that supports get and put operations efficiently.

  • Design a data structure that maintains a cache with a specified capacity.

  • Implement get(key) function to return value associated with key or -1 if key doesn't exist.

  • Implement put(key, value) function to insert/update key-value pair in cache.

  • Invalidate least recently used item when cache reaches its capacity.

  • Handle different types of operations efficiently based on input....read more

Q38. Minimum Number of Jumps Problem

Given an array ARR of N integers, determine the minimum number of jumps required to reach the last index of the array (i.e., N - 1). From any index i, you can jump to an index i ...read more

Ans.

The problem involves finding the minimum number of jumps required to reach the last index of an array, where each element indicates the maximum distance that can be jumped from that position.

  • Use a greedy approach to keep track of the farthest reachable index and the current end of the jump.

  • Iterate through the array, updating the farthest reachable index and incrementing the jump count when necessary.

  • Return the jump count as the minimum number of jumps needed to reach the last...read more

Q39. 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.

Q40. 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.

Q41. 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

Q42. 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

Ans.

Implement a wildcard pattern matching algorithm to determine if a given wildcard pattern matches a text string completely.

  • Create a dynamic programming matrix to store intermediate results

  • Handle cases for '?' and '*' characters separately

  • Check if the characters in the pattern and text match accordingly

  • Return 'True' if the text matches the pattern, otherwise 'False'

Q43. Job Sequencing Problem Statement

You are provided with a N x 2 2-D array called Jobs consisting of N jobs. In this array, Jobs[i][0] represents the deadline of the i-th job, while Jobs[i][1] indicates the profi...read more

Ans.

Maximize profit by scheduling jobs within their deadlines.

  • Sort the jobs based on their profits in descending order.

  • Iterate through the sorted jobs and schedule them based on their deadlines.

  • Keep track of the maximum profit achievable by scheduling jobs within their deadlines.

Q44. Rat In a Maze Problem Statement

Given a N * N maze with a rat placed at position MAZE[0][0], find and print all possible paths for the rat to reach its destination at MAZE[N-1][N-1]. The rat is allowed to move ...read more

Ans.

The problem involves finding all possible paths for a rat to reach its destination in a maze.

  • Use backtracking to explore all possible paths in the maze.

  • Mark visited cells to avoid revisiting them.

  • Return the path once the destination is reached.

  • Handle edge cases like blocked cells and out-of-bounds movements.

Frequently asked in,

Q45. Validate Binary Search Tree Problem Statement

Given a binary tree with 'N' nodes, determine if it is a Binary Search Tree (BST). Return true if the tree is a BST, otherwise return false.

Example:

Input:
1 2 3 4...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 values less than the node's value.

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

  • Ensure that both the left and right subtrees are also binary search trees.

  • Traverse the tree in-order and check if the elements are in sorted order.

  • Use a recursive function to validate each node's value against its sub...read more

Q46. Minimum Knight Moves Problem

Given a square chessboard of size N x N, determine the minimum number of moves a knight requires to reach a target position from a starting position.

Input:

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

The problem involves finding the minimum number of moves a knight requires to reach a target position from a starting position on a chessboard.

  • Use Breadth First Search (BFS) algorithm to find the shortest path from starting position to target position.

  • Consider all possible moves of the knight from its current position to explore the chessboard.

  • Keep track of visited positions to avoid revisiting the same position.

  • Calculate the minimum number of steps needed to reach the target...read more

Q47. Time to Burn Tree Problem

You are given a binary tree consisting of 'N' unique nodes and a start node where the burning will commence. The task is to calculate the time in minutes required to completely burn th...read more

Ans.

Calculate the time in minutes required to completely burn a binary tree starting from a given node.

  • Start burning from the given node and spread fire to adjacent nodes each minute

  • Track the time taken for each node to burn completely

  • Return the maximum time taken to burn the entire tree

Q48. Find Minimum in Rotated Sorted Array

You are presented with a sorted array that has been rotated an unknown number of times. The nature of this rotation is such that each element shifts to the right with the la...read more

Ans.

Find the smallest element in a rotated sorted array.

  • Use binary search to find the pivot point where rotation occurs.

  • Compare the element at the pivot point to determine the smallest element.

  • Handle cases where the array is not rotated or has only one element.

  • Time complexity should be O(log(N)) and space complexity O(1).

Q49. Minimum Steps for a Knight to Reach Target

Given a square chessboard of size 'N x N', determine the minimum number of moves a Knight requires to reach a specified target position from its initial position.

Expl...read more

Ans.

Calculate the minimum number of moves a Knight requires to reach a specified target position on a chessboard.

  • Use breadth-first search (BFS) algorithm to find the shortest path for the Knight.

  • Consider all possible moves of the Knight on the chessboard.

  • Keep track of visited positions to avoid revisiting them.

  • Return the minimum number of moves required to reach the target position.

Q50. Count Pairs with Given Sum

Given an integer array/list arr and an integer 'Sum', determine the total number of unique pairs in the array whose elements sum up to the given 'Sum'.

Input:

The first line contains ...read more
Ans.

Count the total number of unique pairs in an array whose elements sum up to a given value.

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

  • Iterate through the array and for each element, check if (Sum - current element) exists in the hashmap.

  • Increment the count of pairs if the complement exists in the hashmap.

  • Divide the count by 2 to avoid counting duplicates like (arr[i], arr[j]) and (arr[j], arr[i]) separately.

1
2
3
4
5
6
Next
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

Recently Viewed
INTERVIEWS
Odoo
No Interviews
SALARIES
Corizo
SALARIES
HALODOC
REVIEWS
Avanti Fellows
No Reviews
COMPANY BENEFITS
AdaniConneX
No Benefits
LIST OF COMPANIES
AdaniConneX
Overview
SALARIES
AdaniConneX
No Salaries
SALARIES
Corizo
JOBS
Avanti Fellows
No Jobs
REVIEWS
AdaniConneX
No Reviews
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