Flipkart
80+ Pitchbook Interview Questions and Answers
Q1. Search In Rotated Sorted Array Problem Statement
Given a sorted array of distinct integers that has been rotated clockwise by an unknown amount, you need to search for a specified integer in the array. For each...read more
Implement a search function to find a specified integer in a rotated sorted array.
Implement a binary search algorithm to find the target integer in the rotated sorted array.
Handle the cases where the target integer may lie in the left or right half of the array after rotation.
Keep track of the mid element and adjust the search space based on the rotation.
Return the index of the target integer if found, else return -1.
Q2. Missing Number Problem Statement
You are provided with an array named BINARYNUMS
consisting of N
unique strings. Each string represents an integer in binary, covering every integer from 0 to N except for one. Y...read more
Find the missing integer in binary form from an array of unique binary strings.
Iterate through the array of binary strings and convert each string to its decimal equivalent.
Calculate the sum of all integers from 0 to N using the formula (N * (N + 1)) / 2.
Subtract the sum of the integers represented by the binary strings from the total sum to find the missing integer.
Convert the missing integer to binary form and return it as a string without leading zeros.
Q3. Smallest Window Problem Statement
Given two strings S
and X
containing random characters, the task is to find the smallest substring in S
which contains all the characters present in X
.
Input:
The first line co...read more
Find the smallest substring in S containing all characters in X.
Use a sliding window approach to find the smallest window in S containing all characters in X.
Keep track of the characters in X using a hashmap.
Slide the window to the right until all characters in X are found, then shrink the window from the left to find the smallest window.
Q4. Median of Subarrays of Specific Size
Given an integer array ARR
of size N
and a specified subarray size M
, calculate and return the median of all subarrays of size M
starting from the left of the array.
The med...read more
Calculate and return the median of all subarrays of a specified size in an integer array.
Iterate through the array and for each subarray of size M, calculate the median.
If the size of the subarray is even, take the average of the two middle numbers as the median.
Return the list of medians for all subarrays of size M.
Q5. Kth Smallest Element in an Unsorted Array
Given an unsorted array arr
of distinct integers and an integer k
, your task is to find the k-th
smallest element in the array.
Input:
The first line of input contains ...read more
Find the k-th smallest element in an unsorted array of distinct integers.
Sort the array and return the k-th element.
Use a priority queue or quickselect algorithm for efficient solution.
Handle edge cases like k being out of bounds or array being empty.
Q6. Counting Nodes in a Complete Binary Tree - Problem Statement
Given the root of a complete binary tree, calculate the total number of nodes in this tree.
A complete binary tree is defined as a binary tree in whi...read more
Count the total number of nodes in a complete binary tree given its root.
Traverse the tree in level order and count the nodes
Use a queue to keep track of nodes at each level
Check for null nodes represented as -1 in the input
Return the total count of nodes in the tree
Q7. Longest Substring Without Repeating Characters Problem Statement
Given a string S
of length L
, determine the length of the longest substring that contains no repeating characters.
Example:
Input:
"abacb"
Output...read more
Find the length of the longest substring without repeating characters in a given string.
Use a sliding window approach to keep track of the longest substring without repeating characters.
Use a hashmap to store the index of each character as it appears in the string.
Update the start index of the window when a repeating character is found.
Calculate the maximum length of the window as you iterate through the string.
Return the maximum length as the result.
Q8. Counting Sort Problem Statement
Ninja is learning about sorting algorithms, specifically those that do not rely on comparisons. Can you help Ninja implement the counting sort algorithm?
Example:
Input:
ARR = {-...read more
Implement counting sort algorithm to sort an array of integers without comparisons.
Count the frequency of each element in the input array.
Calculate the prefix sum of frequencies to determine the position of each element in the sorted array.
Build the sorted array based on the prefix sum.
Time complexity of counting sort is O(n+k), where n is the number of elements and k is the range of input.
Example: Input array {-2, 1, 2, -1, 0} will be sorted as {-2, -1, 0, 1, 2}.
Q9. Shortest Alternate Colored Path Problem
Given a directed graph consisting of 'N' nodes labeled from '0' to 'N-1'. Each edge in the graph is colored either 'red' or 'blue'. The graph may include self-edges and p...read more
The task is to compute the shortest path from node '0' to each node in a directed graph with alternating colored edges.
Create a graph using the given red and blue edges.
Use Breadth First Search (BFS) to find the shortest path from node '0' to each node with alternating colored edges.
If no such path exists, set the length to -1.
Return the array of shortest path lengths for each node.
Q10. Pythagorean Triplets Detection
Determine if an array contains a Pythagorean triplet by checking whether there are three integers x, y, and z such that x2 + y2 = z2 within the array.
Input:
The first line contai...read more
Detect if an array contains a Pythagorean triplet by checking if there are three integers x, y, and z such that x^2 + y^2 = z^2.
Iterate through all possible triplets of numbers in the array and check if they form a Pythagorean triplet.
Use a nested loop to generate all possible combinations of three numbers from the array.
Check if the sum of squares of two numbers is equal to the square of the third number for each triplet.
Return 'yes' if a Pythagorean triplet is found, otherw...read more
Q11. Validate BST Problem Statement
Given a binary tree with N
nodes, determine whether the tree is a Binary Search Tree (BST). If it is a BST, return true
; otherwise, return false
.
A binary search tree (BST) is a b...read more
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 the left and right subtrees are also binary search trees.
Q12. Phone Directory Search Directory
You are given a list/array of strings representing the contacts in a phone directory. The task is to perform a search based on a query string 'str' and return all contacts that ...read more
Implement a phone directory search feature to suggest contacts based on a query string prefix.
Iterate through the contact list to find contacts with the prefix matching the query string.
Display suggestions as the user types each character of the query.
Handle cases where no suggestions are found for a particular prefix by printing 'No suggestions found'.
Q13. 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 - prev, current, and next - to reverse the linked list in O(N) time and O(1) space complexity.
Update the head of the reversed linked list as the last node encountered during the reversal process.
Q14. 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
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 such as out of bounds indices and already visited cells.
Q15. Kth Ancestor in a Binary Tree
You are given an arbitrary binary tree consisting of N
nodes numbered from 1 to N
, an integer K
, and a node TARGET_NODE_VAL
from the tree. Your task is to find the Kth ancestor of ...read more
Find the Kth ancestor of a given node in a binary tree.
Traverse the tree to find the path from the target node to the root node.
Keep track of the ancestors in a list while traversing.
Return the Kth ancestor from the list, or -1 if it doesn't exist.
Q16. Find the Middle of a Linked List
This problem requires you to return a pointer that references the middle node of a singly linked list.
Explanation:
If the number of elements in the linked list is odd, return t...read more
Return a pointer to the middle node of a singly linked list.
Traverse the linked list with two pointers, one moving twice as fast as the other.
When the fast pointer reaches the end, the slow pointer will be at the middle.
If the number of elements is even, return the second middle node.
Q17. Add Two Numbers as Linked Lists
You are given two singly linked lists, where each list represents a positive number without any leading zeros.
Your task is to add these two numbers and return the sum as a linke...read more
Add two numbers represented as linked lists and return the sum as a linked list.
Traverse both linked lists simultaneously while adding corresponding nodes and carry over the sum if needed
Handle cases where one linked list is longer than the other by considering carry over
Create a new linked list to store the sum and return its head node
Q18. Maximum Sum Path from Leaf to Root
Given a binary tree with 'N' nodes, identify the path from a leaf node to the root node that has the maximum sum among all root-to-leaf paths.
Example:
All the possible root t...read more
Find the path from a leaf node to the root node with the maximum sum in a binary tree.
Traverse the binary tree from leaf to root, keeping track of the sum along each path.
Compare the sums of all root-to-leaf paths and find the path with the maximum sum.
Implement a recursive function to traverse the tree and calculate the sum of each path.
Q19. Find All Triplets with Zero Sum
Given an array Arr
consisting of N
integers, find all distinct triplets in the array that sum up to zero.
Explanation:
An array is said to have a triplet {Arr[i], Arr[j], Arr[k]}...read more
Find all distinct triplets in an array that sum up to zero.
Use a nested loop to iterate through all possible triplets in the array.
Sort the array to easily identify duplicates and skip them.
Check for triplets with sum zero and add them to the result list.
Q20. K Closest Points to Origin Problem Statement
Your house is located at the origin (0,0) of a 2-D plane. There are N
neighbors living at different points on the plane. Your goal is to visit exactly K
neighbors wh...read more
Find the K closest points to the origin in a 2-D plane using Euclidean Distance.
Calculate the Euclidean Distance for each point from the origin
Sort the points based on their distances from the origin
Return the first K points as the closest neighbors
Q21. Longest Palindromic Substring Problem Statement
You are provided with a string STR
of length N
. The goal is to identify the longest palindromic substring within this string. In cases where multiple palindromic ...read more
Identify the longest palindromic substring in a given string.
Iterate through the string and expand around each character to find palindromes
Keep track of the longest palindrome found
Return the longest palindrome with the smallest start index
Q22. Palindrome Partitioning Problem Statement
You are given a string S
. Your task is to partition S
such that every substring of the partition is a palindrome. Your objective is to return all possible palindrome pa...read more
Partition a string into palindromes and return all possible configurations.
Use backtracking to generate all possible palindrome partitions
Check if each substring is a palindrome before adding it to the partition
Return all valid partitions as an array of strings
Q23. Problem: Min Steps to One
Your task is to determine and return the minimum number of steps required to reduce a given positive integer 'N' down to 1.
You can perform one of the following three steps:
1) Subtrac...read more
Find the minimum number of steps to reduce a positive integer to 1 using given operations.
Use dynamic programming to keep track of minimum steps for each number from 1 to N.
Consider all three possible operations for each number and choose the one with minimum steps.
Handle edge cases like when N is less than 1 or when N is not a positive integer.
Q24. Largest BST Subtree Problem Statement
You are given a binary tree with 'N' nodes. Your task is to determine the size of the largest subtree within the binary tree which is also a Binary Search Tree (BST).
Prope...read more
Find the size of the largest subtree in a binary tree that is also a Binary Search Tree.
Traverse the tree in a bottom-up manner to check if each subtree is a BST.
Keep track of the size of the largest BST subtree encountered so far.
Use recursion to solve this problem efficiently.
Example: For the input 1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1, the largest BST subtree has a size of 3.
Q25. Detect Cycle in a Directed Graph
You are provided with a directed graph composed of 'N' nodes. You have a matrix called 'EDGES' with dimensions M x 2, which specifies the 'M' edges in the graph. Each edge is di...read more
Detect cycle in a directed graph using depth-first search (DFS) algorithm.
Use DFS to traverse the graph and detect back edges (edges that point to an ancestor node).
Maintain a visited array to keep track of visited nodes and a recursion stack to keep track of nodes in the current path.
If a back edge is found during traversal, a cycle exists in the graph.
Return true if a cycle is detected, false otherwise.
Q26. LRU Cache Design Question
Design a data structure for a Least Recently Used (LRU) cache that supports the following operations:
1. get(key)
- Return the value of the key if it exists in the cache; otherwise, re...read more
Design a Least Recently Used (LRU) cache data structure that supports get and put operations with capacity constraint.
Use a combination of hashmap and doubly linked list to efficiently implement the LRU cache.
Keep track of the least recently used item and update it accordingly when inserting new items.
Ensure to handle the capacity constraint by evicting the least recently used item when the cache is full.
Implement get(key) and put(key, value) operations as per the specified r...read more
Q27. The Skyline Problem
Compute the skyline of given rectangular buildings in a 2D city, eliminating hidden lines and forming the outer contour of the silhouette when viewed from a distance. Each building is descri...read more
Compute the skyline of given rectangular buildings in a 2D city, eliminating hidden lines and forming the outer contour of the silhouette.
Iterate through the buildings and create a list of critical points (x, y) where the height changes.
Sort the critical points based on x-coordinate and process them to form the skyline.
Merge consecutive horizontal segments of equal height into one to ensure no duplicates.
Return the final list of key points representing the skyline.
Example: In...read more
Q28. Find K-th Smallest Element in BST
Given a binary search tree (BST) and an integer K
, the task is to find the K-th smallest element in the BST.
Example:
Input:
BST: Order of elements in increasing order is { 2, ...read more
Find the K-th smallest element in a binary search tree (BST).
Perform an in-order traversal of the BST to get elements in increasing order.
Keep track of the count of visited nodes to find the K-th smallest element.
Return the K-th smallest element once the count matches K.
Q29. Circular Move Problem Statement
You have a robot currently positioned at the origin (0, 0) on a two-dimensional grid, facing the north direction. You are given a sequence of moves in the form of a string of len...read more
Determine if a robot's movement path is circular on a 2D grid given a sequence of moves.
Create a set of directions to keep track of the robot's movement (N, E, S, W).
Simulate the robot's movement based on the given sequence of moves.
Check if the robot returns to the starting position after completing the moves.
Q30. Modify this code to find the maximum subtree in tree which is a BST. Maximum subtree means subtree goes upto its leaves from any node. Modify the code again to find the maximum tree which is a BST. BST can lie...
read moreModify code to find maximum BST subtree and maximum BST tree in a given tree.
Create a function to check if a given tree is a BST
Traverse the tree and check if each subtree is a BST
Keep track of the maximum BST subtree found so far
To find maximum BST tree, check if each node can be the root of a BST
Keep track of the maximum BST tree found so far
Q31. Trapping Rain Water Problem Statement
You are given a long type array/list ARR
of size N
, representing an elevation map. The value ARR[i]
denotes the elevation of the ith
bar. Your task is to determine the tota...read more
Calculate the total amount of rainwater that can be trapped between given elevations in an array.
Iterate through the array and calculate the maximum height on the left and right of each bar.
Calculate the amount of water that can be trapped at each bar by taking the minimum of the maximum heights on the left and right.
Sum up the trapped water at each bar to get the total trapped water for the entire array.
Q32. Next Permutation Problem Statement
You are given a permutation of 'N' integers. A sequence of 'N' integers is considered a permutation if it includes all integers from 1 to 'N' exactly once. Your task is to rea...read more
The task is to rearrange a given permutation of 'N' integers to form the lexicographically next greater permutation.
Iterate from right to left to find the first element that is smaller than the element to its right.
Swap this element with the smallest element to its right that is greater than it.
Reverse the elements to the right of the swapped element to get the lexicographically next greater permutation.
Q33. Print the Kth Digit
Given three non-negative integers N, M, and K, compute the Kth digit from the right in the number obtained from N raised to the power M (i.e., N ^ M).
Input:
The first line contains an integ...read more
The task is to find the Kth digit from the right in the number obtained from N raised to the power M.
Iterate through the digits of N^M from right to left
Keep track of the position of the current digit
Return the digit at position K from the right
Q34. Find the Longest Palindromic Substring
Given a string ‘S’ composed of lowercase English letters, your task is to identify the longest palindromic substring within ‘S’.
If there are multiple longest palindromic ...read more
Find the longest palindromic substring in a given string, returning the rightmost one if multiple exist.
Use dynamic programming to check for palindromes within the string.
Start by checking for palindromes of length 1 and 2, then expand to longer substrings.
Keep track of the longest palindrome found and its starting index.
Return the substring starting from the index of the longest palindrome found.
Q35. Spell Checker Problem Statement
You are provided with a list of strings, DICTIONARY[]
, representing the correct spellings of words, and a query string QUERY
that may contain misspelled words. Your task is to ve...read more
Implement a spell checker function that suggests correct spellings from a dictionary for a given query string.
Iterate through the dictionary to check for matching prefixes with the query string.
Return a list of suggestions if the query string is misspelled, otherwise return an empty list.
Handle multiple test cases by looping through each case independently.
Q36. There is code like var i; { .. var j; .. } var k; .. var a; { .. var c; { var i; } .. var d; .. } For simplicity you may assume that there is only one variable declaration on 1 line. Now given a line number, yo...
read moreAlgorithm to determine valid variables on a given line of code.
Create a stack to keep track of variable declarations
Traverse the code line by line
When encountering a variable declaration, push it onto the stack
When encountering a closing brace, pop all variables declared within that scope
Return all variables still on the stack when reaching the given line number
Q37. Is Height Balanced Binary Tree Problem Statement
Determine if the given binary tree is height-balanced. A tree is considered height-balanced when:
- The left subtree is balanced.
- The right subtree is balanced.
- T...read more
Determine if a given binary tree is height-balanced by checking if left and right subtrees are balanced and their height difference is at most 1.
Check if the left subtree is balanced
Check if the right subtree is balanced
Calculate the height difference between the left and right subtrees
Return 'True' if all conditions are met, otherwise return 'False'
Q38. Ceil Value from BST Problem Statement
Given a Binary Search Tree (BST) and an integer, write a function to return the ceil value of a particular key in the BST.
The ceil of an integer is defined as the smallest...read more
Ceil value of a key in a Binary Search Tree (BST) is found by returning the smallest integer greater than or equal to the given number.
Traverse the BST to find the closest value greater than or equal to the key.
Compare the key with the current node value and update the ceil value accordingly.
Recursively move to the left or right subtree based on the comparison.
Return the ceil value once the traversal is complete.
Q39. Design a Constant Time Data Structure
Create a data structure that maintains mappings between keys and values, supporting the following operations in constant time:
1. INSERT(key, value): Add or update the inte...read more
Design a constant time data structure to maintain mappings between keys and values with various operations.
Use a hash table to achieve constant time complexity for INSERT, DELETE, SEARCH, and GET operations.
Keep track of the number of key-value pairs for GET_SIZE operation.
Check if the hash table is empty for IS_EMPTY operation.
Return true or false for SEARCH operation based on key existence.
Return the value associated with the key for GET operation, or -1 if not found.
Q40. Pattern Matching Problem Statement
Given a pattern as a string and a set of words, determine if the pattern and the words list align in the same sequence.
Input:
T (number of test cases)
For each test case:
patte...read more
Given a pattern and a list of words, determine if the words align with the pattern.
Iterate through the pattern and words list simultaneously to check for alignment.
Use a hashmap to store the mapping between characters in the pattern and words.
Return 'True' if the mapping aligns with the order of characters in the pattern, else return 'False'.
Q41. Input : 4 jars and 50 balls of different colors (Red, Green, Yellow, Blue) where each jar can contain a maximum of 100 balls.Problem : When a user draws a red ball he loses his money while if he draws a ball of...
read moreArrange balls in 4 jars to maximize probability of user losing money when drawing a red ball.
Place all red balls in one jar and the rest in the other jars
Ensure that the jar with red balls has the highest probability of being chosen
Randomize the placement of the jars to add an element of chance
Q42. K-th Largest Number in a BST
Given a binary search tree (BST) consisting of integers and containing 'N' nodes, your task is to find and return the K-th largest element in this BST.
If there is no K-th largest e...read more
Find the K-th largest element in a BST.
Perform reverse in-order traversal of the BST to find the K-th largest element.
Keep track of the count of visited nodes to determine the K-th largest element.
Return -1 if there is no K-th largest element in the BST.
Q43. Problem: Search In Rotated Sorted Array
Given a sorted array that has been rotated clockwise by an unknown amount, you need to answer Q
queries. Each query is represented by an integer Q[i]
, and you must determ...read more
Search for integers in a rotated sorted array efficiently.
Use binary search to efficiently search for integers in the rotated sorted array.
Handle the rotation of the array while performing binary search.
Return the index of the integer if found, else return -1.
Q44. Count Subarrays with Sum Divisible by K
Given an array ARR
and an integer K
, your task is to count all subarrays whose sum is divisible by the given integer K
.
Input:
The first line of input contains an integer...read more
Count subarrays with sum divisible by K in an array.
Iterate through the array and keep track of the prefix sum modulo K.
Use a hashmap to store the frequency of each prefix sum modulo K.
For each prefix sum, increment the count by the frequency of (prefix sum - K) modulo K.
Handle the case when prefix sum itself is divisible by K.
Return the total count of subarrays with sum divisible by K.
Q45. Given n sequences, and starting and stopping point of every sequence with its score. For eg. no of sequences = 5 start stop score 0 4 4 3 10 11 6 8 8 7 15 10 11 15 4 All scores are positive. You have to find th...
read moreGiven n sequences with start, stop and score, find maximum subset of non-overlapping sequences with maximum total score.
Sort the sequences by their end points.
Use dynamic programming to find the maximum sum of non-overlapping sequences.
Keep track of the previous non-overlapping sequence with maximum sum.
Return the maximum sum and the corresponding non-overlapping sequences.
The time complexity of retrieving the minimum element from a max heap is O(1).
Retrieving the minimum element from a max heap involves accessing the root node, which is always the minimum element in a max heap.
Since the root node can be directly accessed in constant time, the time complexity is O(1).
Q47. Running Median Problem
Given a stream of integers, calculate and print the median after each new integer is added to the stream.
Output only the integer part of the median.
Example:
Input:
N = 5
Stream = [2, 3,...read more
Calculate and print the median after each new integer is added to the stream.
Use two heaps - a max heap to store the smaller half of the numbers and a min heap to store the larger half.
Keep the sizes of the two heaps balanced to efficiently calculate the median.
If the total number of elements is odd, the median will be the top element of the max heap.
If the total number of elements is even, the median will be the average of the top elements of the two heaps.
Q48. Given two string str and pat. Find minimum window in str which contains all characters from string pat
Find minimum window in a string which contains all characters from another string.
Use a sliding window approach
Create a frequency map of characters in pat
Iterate through str and update frequency map
Keep track of minimum window that contains all characters
Return minimum window
Q49. Given an array of integers, find Pythagorean triplets. i.e. find a,b and c which satisfies a^2 + b^2 = c^2. Integers could be positive or negative
Find Pythagorean triplets in an array of integers.
Loop through the array and pick two numbers at a time.
Calculate the sum of squares of the two numbers.
Check if the sum is a perfect square.
If yes, then it is a Pythagorean triplet.
Repeat until all possible combinations are checked.
Q50. Given a BST, find the node which contains the value which is equal to or greater than the input value?
Find node in BST with value equal to or greater than input value.
Start at root node
If input value is less than current node value, move to left child
If input value is greater than or equal to current node value, move to right child
Repeat until node with desired value is found or null is reached
Q51. Implement a phone book. You can search either by name or phone number. You can search by prefix also. Write whole code with proper syntax
Implement a phone book with search by name or phone number and prefix.
Create an array of strings to store contacts
Implement a function to add contacts to the array
Implement a function to search by name or phone number
Implement a function to search by prefix
Use regular expressions to match prefixes
Zombie process is a terminated process that has completed execution but still has an entry in the process table. Orphan process is a process whose parent process has terminated.
Zombie process is created when a child process completes execution but its parent process has not yet read its exit status.
Zombie processes consume system resources and should be cleaned up by the parent process using wait() system call.
Orphan process is a process whose parent process has terminated be...read more
Q53. WAP to find a continuous subset whose sum is divisible by 7. We are given a array of number (-ve and +ve). calculate the complexity of your algorithm?
WAP to find a continuous subset divisible by 7 from an array of numbers. Calculate algorithm complexity.
Iterate through the array and calculate the prefix sum modulo 7 at each index.
Store the prefix sum modulo 7 in a hash table with the index as the value.
If a prefix sum modulo 7 is already in the hash table, the subarray between the two indices has a sum divisible by 7.
Time complexity is O(n) and space complexity is O(n).
Q54. Given a BST, how would you return the kth smallest element. Cover all the corner cases with time complexity logn?
Returning kth smallest element in a BST with time complexity logn.
Perform in-order traversal and keep track of count until kth element is reached
If kth element is found, return it
If kth element is not found, continue traversal
If traversal is complete and kth element is not found, return null
Time complexity is logn as we only traverse the height of the tree
Q55. Which is the fastet method to sort an almost sorted array: quick sort,bubble sort,merge sort,shell sort
The fastest method to sort an almost sorted array is shell sort.
Shell sort has a time complexity of O(n log n) which is faster than bubble sort and insertion sort.
Quick sort and merge sort have a time complexity of O(n log n) but they are not optimized for almost sorted arrays.
Shell sort works by comparing elements that are far apart first and then gradually reducing the gap between them.
Example: If the array is [1, 3, 2, 4, 5] and it is almost sorted, shell sort will first c...read more
Q56. Given a list of stars and their distances from the earth.Find an efficient solution to find the k closest stars to earth?
Efficient solution to find k closest stars to earth from a list of stars and their distances.
Use a priority queue to store the distances of stars from earth.
Iterate through the list of stars and add their distances to the priority queue.
Pop k elements from the priority queue to get the k closest stars to earth.
Q57. Given a 2-dimensional array of integers, find the value 1 in the array, and set all those rows, and columns to 1, which contains one of the values as 1
Given a 2D array of integers, set rows and columns to 1 if they contain 1.
Iterate through the array to find the index of 1
Use two arrays to keep track of rows and columns with 1
Iterate through the rows and columns arrays to set values to 1
Q58. Given s string, Find max size of a sub-string, in which no duplicate chars present?
Find max size of a sub-string with no duplicate characters in a given string.
Use a sliding window approach with two pointers.
Maintain a hash set to keep track of unique characters.
Update the maximum length of the substring as you iterate through the string.
Q59. Implement LRU cache. Write a code for this. LRU cache supports 3 operations, put(key, value) get(key) remove(key)
Implement LRU cache with put, get, and remove operations.
LRU stands for Least Recently Used.
The cache should have a maximum capacity.
When the cache is full, the least recently used item should be removed.
When an item is accessed, it should be moved to the front of the cache.
Use a doubly linked list and a hash map to implement the cache efficiently.
Q60. Given an array find any three numbers which sum to zero. Give the best algorithm?
Algorithm to find any three numbers in an array that sum to zero.
Sort the array in ascending order.
Loop through the array and fix the first number.
Use two pointers to find the other two numbers that sum to the negative of the fixed number.
If found, return the three numbers.
If not found, move to the next number and repeat the process.
Time complexity: O(n^2)
Design a cab booking system for efficient and convenient service.
Implement a user-friendly mobile app and website for booking cabs.
Include features like real-time tracking, fare estimation, and driver ratings.
Integrate payment options for seamless transactions.
Develop a robust backend system to manage bookings, drivers, and customer support.
Utilize algorithms for efficient route planning and matching drivers with passengers.
Q62. What is a hash table? Explain how they work (hash function and buckets)?
A hash table is a data structure that stores key-value pairs and uses a hash function to map keys to buckets.
Hash function takes a key and returns an index to a bucket
Collisions occur when multiple keys map to the same bucket
Collision resolution techniques include chaining and open addressing
Example: Dictionary in Python uses hash tables to store key-value pairs
Thrashing in operating systems occurs when the system is spending more time swapping data between memory and disk than actually executing tasks.
Occurs when the system is constantly swapping data between memory and disk
Causes a significant decrease in performance as the system is unable to effectively execute tasks
Usually happens when the system is overloaded with too many processes or lacks sufficient memory
Can be mitigated by optimizing memory usage or reducing the number of...read more
Q64. What is the complexity of retrieving min element from a max heap
Retrieving min element from a max heap has a time complexity of O(log n).
The min element is always the leftmost leaf node in the last level of the heap.
To retrieve it, swap it with the last element in the heap and remove it.
Then, bubble down the new root to maintain the max heap property.
Examples: retrieving the smallest number in a priority queue implemented as a max heap.
Examples: retrieving the smallest element in a max heap of integers.
Q65. Implement next_permutation function (similar to what is in algorithm.h)
next_permutation function generates the next greater lexicographic permutation of a sequence
The function modifies the sequence to its next permutation if possible
If the sequence is already the largest permutation, it rearranges it to the smallest permutation
The function returns true if a next permutation exists, else false
The sequence must be sorted in non-descending order before calling the function
Q66. Given a number, compute the nearest palindrome number. This palindrome number should be greater than given number
Compute the nearest palindrome number greater than given number.
Convert the given number to string and reverse it.
Add the reversed string to the original number and check if it's a palindrome.
If not, repeat the process until a palindrome is found.
If the original number is already a palindrome, add 1 to it and repeat the process.
Q67. Check whether given Binary Tree is a Binary Search Tree. Discuss various approaches?
Check if a Binary Tree is a Binary Search Tree
Inorder traversal of BST should be in ascending order
Check if left child is less than parent and right child is greater than parent
Recursively check left and right subtrees
Use min and max values to check if nodes are within valid range
Q68. Write a code to check if a tree is BST or not
Code to check if a tree is BST or not
Check if left subtree is BST
Check if right subtree is BST
Check if max value in left subtree is less than root
Check if min value in right subtree is greater than root
Q69. Write code to find sum of two numbers stored as linked list.(LSB at last node) and head of each list is given
Code to find sum of two numbers stored as linked list.
Traverse both lists simultaneously and add corresponding nodes
Keep track of carry and add it to next sum
Create a new node for each sum and move to next node
Indexing in databases is a technique used to improve the speed of data retrieval by creating a data structure that allows for quick lookups.
Indexes are created on columns in a database table to speed up the retrieval of rows that match a certain condition.
Types of indexes include B-tree, hash, and bitmap indexes.
Indexes can improve the performance of SELECT queries but may slow down INSERT, UPDATE, and DELETE operations.
Examples of indexing include creating an index on a 'use...read more
FCFS stands for First-Come, First-Served. It is a scheduling algorithm used in operating systems.
FCFS is a non-preemptive scheduling algorithm where the process that arrives first is executed first.
It is a simple and easy-to-understand scheduling algorithm.
Example: If processes P1, P2, and P3 arrive in that order, they will be executed in the same order - P1, P2, P3.
FCFS can lead to the problem of 'convoy effect' where short processes are stuck behind long processes.
Q72. Given a large list of numbers in a file and a very small amount of memory, sort the file
Sort a large file of numbers with limited memory
Use external sorting algorithms like merge sort or quick sort
Divide the file into smaller chunks that can fit into memory
Sort each chunk and merge them together using a priority queue
Consider using disk-based sorting techniques like replacement selection
Optimize I/O operations to minimize disk access
Q73. Write code to print elements on the path from root to leaf node having the maximum sum
Code to print elements on path from root to leaf node with max sum
Traverse the tree and keep track of the maximum sum path
Use recursion to traverse the tree
Print the path when a leaf node with maximum sum is reached
Q74. Write a program to check if a binary tree is balanced
Program to check if a binary tree is balanced
Calculate height of left and right subtrees recursively
Check if the difference in height is not more than 1
Repeat for all nodes in the tree
Time complexity: O(nlogn) or O(n)
Space complexity: O(h) where h is the height of the tree
Q75. -> How to reverse a doubly linked list?
To reverse a doubly linked list, swap the next and previous pointers of each node.
Start from the head of the list
Swap the next and previous pointers of each node
Update the head and tail pointers accordingly
Q76. Tell about zombie process?
A zombie process is a process that has completed execution but still has an entry in the process table.
Zombie processes occur when a parent process does not properly wait for its child process to terminate.
The zombie process remains in the process table until the parent process reads its exit status.
Zombie processes do not consume system resources but can accumulate if not properly handled.
They can be identified using the 'ps' command with the 'Z' status.
Zombie processes can ...read more
Q77. Find Nth largest element in the BST
Find Nth largest element in the BST
Traverse the BST in reverse inorder and keep track of count
If count equals N, return the current node's value
If count exceeds N, stop traversing and return null
If count is less than N, continue traversing
Q78. a medium to hard level Tree problem
Implement a tree data structure and perform a medium to hard level operation on it.
Create a Node class with left and right pointers
Implement methods for insertion, deletion, and traversal
Solve a specific problem like finding the lowest common ancestor
Q79. Complexities on hash table?
Hash tables have complexities related to collisions, resizing, and choosing a good hash function.
Collisions occur when two keys map to the same index, requiring a collision resolution strategy.
Resizing can be expensive as all elements need to be rehashed and moved to new locations.
Choosing a good hash function is important to minimize collisions and ensure even distribution of keys.
Examples of collision resolution strategies include chaining and open addressing.
Hash tables ca...read more
Q80. Design airline service.
Design an airline service for booking flights and managing reservations.
Create a user-friendly website or mobile app for customers to search and book flights.
Implement a secure payment system for online bookings.
Develop a system for managing flight schedules, seat availability, and reservations.
Include features for customers to check-in online, select seats, and view flight status.
Offer loyalty programs and discounts for frequent flyers.
Q81. Kth Largest in a BST
Find the Kth largest element in a Binary Search Tree.
Perform reverse inorder traversal to visit nodes in descending order.
Keep track of the count of visited nodes to find the Kth largest element.
Stop traversal once the Kth largest element is found.
More about working at Flipkart
Interview Process at Pitchbook
Top Software Developer Interview Questions from Similar Companies
Reviews
Interviews
Salaries
Users/Month