


100+ Google Interview Questions and Answers for Freshers
Q1. Painter's Partition Problem Statement
Given an array/list representing boards, where each element denotes the length of a board, and a number ‘K’ of available painters, determine the minimum time required to pa...read more
Determine the minimum time required to paint all boards with given constraints.
Use binary search to find the minimum and maximum possible time to paint all boards.
Iterate through the boards and assign them to painters based on the time constraints.
Calculate the total time taken to paint all boards with the assigned painters.
Q2. Special Numbers Problem Statement
Your task is to find the total count of special numbers within a range from 1 to a given integer, 'MAXVAL'. A special number is defined as a number whose digits, when rotated 1...read more
Count the total number of special numbers within a given range by rotating digits 180 degrees.
Create a function to check if a number is a special number by rotating its digits.
Iterate through the range from 1 to MAXVAL and count the special numbers.
Handle the digit rotation mapping for 0, 1, 6, 8, 9.
Return the count of special numbers for each test case.
Q3. Chocolate Distribution Problem
You are given an array/list CHOCOLATES
of size 'N', where each element represents the number of chocolates in a packet. Your task is to distribute these chocolates among 'M' stude...read more
Distribute chocolates among students to minimize the difference between the largest and smallest number of chocolates.
Sort the array of chocolates.
Use sliding window technique to find the minimum difference between the largest and smallest number of chocolates.
Return the minimum difference as the output.
Q4. Say you have three tables WORK, USERS, MANAGERS WORK - work_id - user_id - how_much USERS - user_id - team MANAGERS - manager_id - team If I am a manager, write a select statement to retrieve the work of all us...
read moreWrite a select statement to retrieve work of all users who belong to my team.
Join USERS and WORK tables on user_id
Join MANAGERS and USERS tables on team
Filter by manager_id
Q5. Minimum and Maximum Candy Cost Problem
Ram is in Ninjaland, visiting a unique candy store offering 'N' candies each with different costs. The store has a special offer: for every candy you purchase, you can tak...read more
Find minimum and maximum cost to purchase all candies with special offer of free candies.
Iterate through the candy costs array and sort it in ascending order.
For minimum cost, start from the lowest cost candy and take free candies until reaching the next higher cost candy.
For maximum cost, start from the highest cost candy and take free candies until reaching the next lower cost candy.
Q6. Problem Statement: Minimize the Maximum
You are given an array of integers and an integer K
. For each array element, you can adjust it by increasing or decreasing it by a value of K
. Your goal is to minimize th...read more
Given an array of integers and an integer K, minimize the difference between the maximum and minimum elements after adjusting each element by +/- K.
Sort the array in non-decreasing order.
For each element, calculate the difference between the current element and the next element.
Adjust the element by adding or subtracting K to minimize the difference.
Return the minimum possible difference between the maximum and minimum elements.
Q7. Shopping Spree Problem Statement
Preeti plans to shop for her father's birthday at a store with unlimited quantities of N different items. She has a budget that allows her to buy a maximum of K items. Help Pree...read more
Calculate the number of ways Preeti can purchase items within budget, considering distinct ways.
Use dynamic programming to calculate the number of ways to purchase items within budget
Consider different scenarios where Preeti buys different quantities of each item
Return the result modulo 10^9 + 7 to handle large answers
Q8. Farthest Distance From Lands Problem Statement
Given a binary square matrix 'ARR' with 'N' rows and 'N' columns, where '0' represents water and '1' represents land.
Determine the water cell whose distance to th...read more
Find the water cell farthest from land in a binary matrix using Manhattan distance.
Iterate through the matrix to find all land cells and water cells
Calculate the Manhattan distance of each water cell to the nearest land cell
Return the maximum distance found
Q9. Bridge in Graph Problem Statement
Given an undirected graph with V vertices and E edges, your task is to find all the bridges in this graph. A bridge is an edge that, when removed, increases the number of conne...read more
Find all the bridges in an undirected graph.
Use Tarjan's algorithm to find bridges in the graph.
A bridge is an edge whose removal increases the number of connected components.
Check for bridges by removing each edge and checking the number of connected components.
Return the edges that are bridges in non-decreasing order.
Q10. 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, find max vaccines administered on a specific day during a vaccination drive.
Iterate through each test case and calculate the maximum number of vaccines distributed on the specified day.
Distribute vaccines evenly across days while maximizing the number on the specified day.
Ensure that the sum of vaccines administered does not exceed the maximum allowed.
Consider edge cases like when the number of days is equal to the maximum number of vaccines available.
Q11. Alien Dictionary Problem Statement
You are provided with a sorted dictionary (by lexical order) in an alien language. Your task is to determine the character order of the alien language from this dictionary. Th...read more
Given a sorted alien dictionary, determine the character order of the alien language.
Create a graph data structure to represent the relationships between characters based on the given dictionary.
Perform a topological sort on the graph to determine the character order of the alien language.
Return the character array obtained from the topological sort as the final output.
Q12. Count Ways to Reach the N-th Stair Problem Statement
You are provided with a number of stairs, and initially, you are located at the 0th stair. You need to reach the Nth stair, and you can climb one or two step...read more
Count the number of distinct ways to climb to the Nth stair by climbing one or two steps at a time.
Use dynamic programming to solve the 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 base cases where N=0 and N=1 separately.
Apply modulo 10^9+7 to avoid overflow in the final result.
Q13. Problem: Ninja's Robot
The Ninja has a robot which navigates an infinite number line starting at position 0 with an initial speed of +1. The robot follows a set of instructions which includes ‘A’ (Accelerate) a...read more
Determine the minimum length of instruction sequence for a robot to reach a given target on an infinite number line.
Start at position 0 with speed +1, update position and speed based on 'A' and 'R' instructions
For each test case, find the shortest sequence of instructions to reach the target
Consider both positive and negative positions for the robot
Q14. Swap And Maximize Problem Statement
You are given a circular array consisting of N integers. Your task is to find the maximum sum of the absolute differences between adjacent elements by rearranging the array e...read more
Find the maximum sum of absolute differences between adjacent elements in a circular array by rearranging the elements.
Sort the array in non-decreasing order.
Alternate between picking the smallest and largest elements to maximize the sum of absolute differences.
Calculate the sum of absolute differences between adjacent elements in the rearranged array.
Q15. a / b c / / d e f g Print the nodes in the following order: a, b, c, g, f, e, d, h, i, j, k, l ,m, n, o and so on. Which all data structures are used? Can we use just 1?
Multiple data structures are used to print nodes in a specific order. One data structure cannot be used alone.
The given order suggests a depth-first search traversal of a tree-like structure.
A stack can be used to keep track of the nodes to be visited.
A queue can be used to store the children of a node in the order they are visited.
An array can be used to store the nodes in the required order.
A linked list can be used to connect the nodes in the required order.
Using just one ...read more
Q16. Connecting Ropes with Minimum Cost
You are given 'N' ropes, each of varying lengths. The task is to connect all ropes into one single rope. The cost of connecting two ropes is the sum of their lengths. Your obj...read more
Connect ropes with minimum cost by merging two smallest ropes at a time.
Sort the array of rope lengths in ascending order.
Merge the two smallest ropes at a time and update the cost.
Repeat until all ropes are merged into one.
Return the total cost as the minimum cost to connect all ropes.
Q17. If you had an opportunity to design the Google Suggest system, please let us know how you would approach it and how you would execute the plan in terms of settings up systems like(data stores or databases, inde...
read moreDesigning Google Suggest system
I would start by analyzing user search patterns and frequently searched keywords
Then, I would create a database of these keywords and their associated search results
I would use indexing services to quickly retrieve relevant results for each keyword
I would also implement machine learning algorithms to improve the accuracy of suggestions over time
Q18. Given n pens and n tops, each pen (and each top) having a size different than the other and each pen fitting exactly one top, find the largest pen using minimum number of comparisons. A comparison involves pick...
read moreFind largest pen using minimum comparisons with tops.
Divide pens into two groups and compare largest pen from each group with largest top.
Repeat the process with the group containing the largest pen until only one pen is left.
The remaining pen is the largest pen.
Total number of comparisons required is 2n-3.
Q19. How do you find out if a number is a power of 2? And how do you know if it is an odd number? Write code in the language of your choice
Check if a number is a power of 2 and odd.
To check if a number is a power of 2, use bitwise AND operator with the number and its predecessor. If the result is 0, it is a power of 2.
To check if a number is odd, use modulus operator with 2. If the result is 1, it is odd.
Example code in Python:
def is_power_of_two(num):
return num & (num - 1) == 0
def is_odd(num):
return num % 2 == 1
Q20. Given a source array of integers with possible duplicates and a target integer, write algorithm to find out 2 numbers in source array whose sum is equal to target integer
Algorithm to find 2 numbers in an array whose sum is equal to a target integer
Use a hash table to store the difference between target and each element in the array
Iterate through the array and check if the current element exists in the hash table
Return the pair of elements that sum up to the target integer
Q21. Given n dice, each of 'a' sides and a sum b, return the number of ways in which the sum b can be obtained. How can you reduce the time complexity and space complexity?
Given n dice with 'a' sides and sum b, return no. of ways to obtain b. Optimize time and space complexity.
Use dynamic programming to reduce time complexity
Create a 2D array to store the number of ways to obtain each sum for each number of dice
Use rolling arrays to optimize space complexity
Example: n=2, a=6, b=7 -> 6 ways to obtain sum 7
Example: n=3, a=4, b=8 -> 21 ways to obtain sum 8
Q22. Which is faster: finding an item in a hashtable or in a sorted list? And Why?
Hashtable is faster for finding an item than a sorted list.
Hashtable has constant time complexity O(1) for finding an item.
Sorted list has logarithmic time complexity O(log n) for finding an item.
Hashtable uses hashing to directly access the item's location.
Sorted list requires binary search to find the item's location.
Hashtable is ideal for large datasets with frequent lookups.
Sorted list is ideal for datasets that require frequent insertions and deletions.
Q23. Given 2 machines, each having 64 GB RAM, containing all integers (8 byte), sort the entire 128 GB data. You may assume a small amount of additional RAM. Extend this to sort data stored in 1000 machines
Sort 128 GB data on 2 machines with 64 GB RAM each. Extend to 1000 machines.
Use external sorting algorithm like merge sort or quick sort
Divide data into smaller chunks and sort them individually
Merge sorted chunks using additional RAM
For 1000 machines, use distributed sorting algorithms like MapReduce or Hadoop
Ensure data consistency and fault tolerance in distributed sorting
Q24. In google adwords there are about 30 million ads from 42 lanuages . What will I do review the ads and reject ads that do not comply with specific rules
Reviewing 30 million ads from 42 languages in Google AdWords and rejecting non-compliant ads requires a systematic approach.
Create a set of specific rules and guidelines for ad compliance
Use automated tools to filter out ads that violate the rules
Assign a team of reviewers to manually check the remaining ads
Ensure that the reviewers are fluent in the languages of the ads they are reviewing
Regularly update the rules and guidelines to keep up with changes in the industry
Provide...read more
Q25. How would you change the format of all the phone numbers in 1000 static html pages?
Use a script to iterate through each HTML page, locate phone numbers, and update their format.
Write a script using a programming language like Python or JavaScript to iterate through each HTML page
Use regular expressions to locate phone numbers in the pages
Update the format of the phone numbers as needed (e.g. adding country code, changing separators)
Save the updated HTML pages with the new phone number format
Q26. What are some of the most popular Data interchange formats when using APIs
JSON and XML are the most popular data interchange formats when using APIs.
JSON (JavaScript Object Notation) is a lightweight format that is easy to read and write. It is widely used in web APIs.
XML (Extensible Markup Language) is a more complex format that is also widely used in web APIs.
Other formats include CSV (Comma Separated Values), YAML (YAML Ain't Markup Language), and Protocol Buffers.
Q27. Explain the difference between ArrayList and LinkedList in Java. ArrayList is implemented as a dynamic array, while LinkedList is a doubly linked list. ArrayList provides fast random access (O(1) complexity) bu...
read moreArrayList is preferred for frequent retrieval operations, while LinkedList is suitable for frequent insertions/deletions.
Use ArrayList when you need fast random access and retrieval operations, such as searching for elements in a list.
Choose LinkedList when you need fast insertions/deletions, especially at the beginning or end of the list.
Consider memory overhead and performance trade-offs when deciding between ArrayList and LinkedList.
For example, if you have a list of stude...read more
Q28. What are the advantages and disadvantages of using Java’s synchronized keyword for thread synchronization? The synchronized keyword ensures that only one thread can access a block of code at a time. It prevents...
read moreReentrantLock should be used instead of synchronized when more flexibility and control over locking mechanisms is needed.
Use ReentrantLock when you need to implement custom locking strategies or require advanced features like tryLock() and lockInterruptibly()
ReentrantLock supports fair locking mechanisms, ensuring that threads acquire the lock in the order they requested it
ReentrantLock allows for more fine-grained control over locking and unlocking, reducing the chances of d...read more
Q29. What is the difference between == and .equals() in Java? == checks for reference equality, meaning it compares memory addresses. equals() checks for value equality, which can be overridden in user-defined class...
read moreIn Java, == checks for reference equality while equals() checks for value equality. Misuse of == can lead to logical errors.
Override equals() when you want to compare the actual content of objects in user-defined classes.
Override hashCode() alongside equals() to ensure consistent behavior in hash-based collections.
Implement Comparable interface and override compareTo() for natural ordering of objects.
Q30. How does the Java garbage collector work? Garbage collection in Java automatically reclaims memory occupied by unused objects. The JVM has different types of GC algorithms, including Serial, Parallel, CMS, and...
read moreGarbage collection in Java automatically reclaims memory occupied by unused objects using different algorithms and memory regions.
Force garbage collection in Java using System.gc() or Runtime.getRuntime().gc()
Not recommended to force garbage collection as it can cause performance issues and disrupt the JVM's optimization
Example: System.gc();
Q31. What are the main features of Java 8? Java 8 introduced lambda expressions, enabling functional-style programming. The Stream API allows efficient data processing with map, filter, and reduce operations. Defaul...
read moreLambda expressions in Java 8 improve readability and maintainability by allowing concise and functional-style programming.
Lambda expressions reduce boilerplate code by providing a more compact syntax for implementing functional interfaces.
They make code more readable by focusing on the behavior being passed as an argument, rather than the mechanics of how it is implemented.
Lambda expressions enable developers to write more modular and reusable code, leading to better maintain...read more
Q32. How will improve the revenue of the cafeteria of the office.
By introducing new menu items, optimizing pricing strategy, and improving the overall dining experience.
Conduct a survey to understand the preferences of employees
Introduce healthy and affordable meal options
Offer discounts for bulk orders or loyalty programs
Partner with local vendors to source fresh ingredients
Improve the ambiance and seating arrangements
Implement online ordering and delivery services
Q33. Name some popular APIs for each of these Social Commerce service(llike a photo service etc)
Popular APIs for Social Commerce services
Facebook Graph API for social media integration
Instagram API for photo sharing and tagging
Twitter API for real-time updates and customer engagement
Pinterest API for product discovery and sharing
Google Maps API for location-based services
PayPal API for secure payment processing
Q34. What do you know about software engineering and theoretically knowledge
Software engineering is the process of designing, developing, testing, and maintaining software.
It involves using engineering principles to create high-quality software
It includes various stages such as requirements gathering, design, coding, testing, and maintenance
Theoretical knowledge includes understanding of algorithms, data structures, programming languages, and software design patterns
Examples of software engineering practices include Agile, Waterfall, and DevOps metho...read more
Q35. Explain the difference between ArrayList and LinkedList in Java. When would you choose one over the other?
ArrayList and LinkedList are both classes in Java that implement the List interface, but they have different underlying data structures.
ArrayList uses a dynamic array to store elements, providing fast random access but slower insertion and deletion.
LinkedList uses a doubly linked list to store elements, providing fast insertion and deletion but slower random access.
Choose ArrayList when you need fast random access and know the size of the list beforehand. Choose LinkedList wh...read more
Q36. What is a Java Stream, and how does it differ from an Iterator? Explain how Streams can be used to process collections efficiently.
Java Stream is a sequence of elements that supports functional-style operations. It differs from Iterator by allowing for more concise and declarative code.
Streams can process elements in a collection in a declarative way, allowing for functional-style operations like map, filter, and reduce.
Streams do not store elements, they operate on the source data structure (e.g., List) directly.
Iterators are used to iterate over a collection sequentially, while Streams can perform para...read more
Q37. Explain the concept of immutability in Java. How does the String class achieve immutability, and what are the advantages of immutable objects?
Immutability in Java means objects cannot be modified after creation. String class achieves immutability by not allowing changes to its value.
Immutability means once an object is created, its state cannot be changed.
String class achieves immutability by making its value final and not providing any methods to modify it.
Advantages of immutable objects include thread safety, caching, and easier debugging.
Example: String str = "Hello"; str.concat(" World"); // This does not chang...read more
Q38. What is the difference between final, finally, and finalize in Java? Provide examples to illustrate their usage.
final, finally, and finalize have different meanings in Java.
final is a keyword used to declare constants, immutable variables, or prevent method overriding.
finally is a block used in exception handling to execute code after try-catch block.
finalize is a method used for cleanup operations before an object is garbage collected.
Q39. Explain the Singleton design pattern in Java. How can you implement it safely to ensure thread safety?
Singleton design pattern ensures a class has only one instance and provides a global point of access to it.
Create a private static instance of the class.
Provide a public static method to access the instance.
Use synchronized keyword or double-checked locking to ensure thread safety.
Q40. Can you explain the difference between method overloading and method overriding in Java? Provide examples where each should be used.
Method overloading is when multiple methods have the same name but different parameters, while method overriding is when a subclass provides a specific implementation of a method in its superclass.
Method overloading is achieved within the same class by having multiple methods with the same name but different parameters.
Method overriding occurs in a subclass that provides a specific implementation of a method that is already provided by its superclass.
Method overloading is use...read more
Q41. What are Java annotations, and how are they used in frameworks like Spring? Explain the difference between built-in and custom annotations.
Java annotations are metadata that provide data about a program but do not affect the program itself. They are used in frameworks like Spring to configure and customize behavior.
Java annotations are used to provide metadata about a program, such as information about classes, methods, or fields.
In frameworks like Spring, annotations are used to configure various aspects of the application, such as defining beans, handling transactions, or mapping URLs.
Built-in annotations in J...read more
Q42. What are the advantages and disadvantages of using Java’s synchronized keyword for thread synchronization? Can you explain how the ReentrantLock compares to synchronized?
Using synchronized keyword for thread synchronization in Java has advantages like simplicity and disadvantages like potential for deadlock. ReentrantLock offers more flexibility and control.
Advantages of synchronized keyword: simplicity, built-in support in Java
Disadvantages of synchronized keyword: potential for deadlock, lack of flexibility
ReentrantLock offers more control over locking, ability to try and lock with timeout, ability to create fair locks
ReentrantLock can be u...read more
Q43. How does the Java garbage collector work? Can you describe the different types of garbage collection algorithms available in Java?
The Java garbage collector is responsible for automatically managing memory by reclaiming unused objects.
The garbage collector in Java runs in the background and automatically reclaims memory from objects that are no longer in use.
There are different types of garbage collection algorithms in Java, such as Serial, Parallel, CMS, G1, and ZGC.
Each garbage collection algorithm has its own characteristics and is suitable for different types of applications and workloads.
Q44. What is the Java Memory Model, and how does it affect multithreading and synchronization? How does volatile help ensure memory visibility?
The Java Memory Model defines how threads interact through memory and how synchronization ensures data consistency.
Java Memory Model specifies how threads interact with memory, ensuring data consistency
It defines rules for reading and writing shared variables in a multithreaded environment
Synchronization mechanisms like synchronized blocks and locks ensure proper visibility and ordering of memory operations
The 'volatile' keyword in Java ensures that changes made by one thread...read more
Q45. How do Java Streams handle parallel processing? What are the potential pitfalls of using parallel streams, and how can they be mitigated?
Java Streams handle parallel processing by splitting the data into multiple chunks and processing them concurrently.
Java Streams use the Fork/Join framework to split the data into chunks and process them in parallel.
Potential pitfalls include increased overhead due to thread management, potential race conditions, and decreased performance for small datasets.
Pitfalls can be mitigated by ensuring thread safety, avoiding stateful operations, and testing performance with differen...read more
Q46. What is the difference between == and .equals() in Java? When should each be used, and what issues can arise from improper usage?
In Java, == compares memory addresses while .equals() compares values of objects. Improper usage can lead to unexpected results.
Use == to compare primitive data types or check if two objects reference the same memory address.
Use .equals() to compare the values of objects, such as strings or custom classes.
Improper usage of == with objects can lead to unexpected results as it compares memory addresses, not values.
Q47. What are the main features of Java 8? Can you explain how lambdas and the Stream API have changed the way Java applications are written?
Java 8 introduced features like lambdas and Stream API which have revolutionized the way Java applications are written.
Lambdas allow for more concise and readable code by enabling functional programming paradigms.
Stream API provides a way to process collections of objects in a functional style, making code more expressive and efficient.
Java 8 also introduced default methods in interfaces, allowing for backward compatibility without breaking existing code.
The new Date and Time...read more
Q48. What are functional interfaces in Java? How do they work with lambda expressions? Provide an example of a custom functional interface.
Functional interfaces in Java are interfaces with a single abstract method. They can be used with lambda expressions for functional programming.
Functional interfaces have only one abstract method, but can have multiple default or static methods.
Lambda expressions can be used to implement the abstract method of a functional interface concisely.
An example of a custom functional interface is 'Calculator' with a single abstract method 'calculate'.
Q49. Describe the differences between checked and unchecked exceptions in Java. Provide examples and explain how to handle them properly.
Checked exceptions are checked at compile time, while unchecked exceptions are not. Proper handling involves either catching or declaring the exception.
Checked exceptions must be either caught or declared in the method signature using the 'throws' keyword.
Unchecked exceptions do not need to be caught or declared, but can still be handled using try-catch blocks.
Examples of checked exceptions include IOException and ClassNotFoundException, while examples of unchecked exceptions...read more
Q50. Hotel Room Booking Problem
You are managing a hotel with 10 floors numbered from 0 to 9. Each floor contains 26 rooms labeled from A to Z. You will receive a sequence of strings representing room bookings where...read more
Given a sequence of room bookings and freeings, find the room that is booked the most times.
Create a hashmap to store the count of each room booking.
Iterate through the sequence of bookings and freeings, updating the count in the hashmap.
Find the room with the highest count and return it. In case of a tie, return the lexicographically smaller room.
Example: For input n = 6, Arr[] = {"+1A", "+3E", "-1A", "+4F", "+1A", "-3E"}, the output would be "1A".
Q51. 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
Q52. what is dsa and what is advantages
DSA stands for Data Structures and Algorithms. It is essential for efficient problem-solving in software development.
DSA helps in organizing and managing data effectively
It improves the efficiency and performance of algorithms
Common data structures include arrays, linked lists, trees, graphs
Common algorithms include sorting, searching, and dynamic programming
Q53. Majority Element - II Problem Statement
Given an array/list ARR
of integers with length 'N', identify all elements that appear more than floor(N/3)
times within the array/list.
Input:
T (number of test cases)
Fo...read more
Q54. what is cpp and its use case
C++ is a programming language used for developing software applications.
C++ is a high-level programming language known for its performance and flexibility.
It is commonly used for developing system software, game engines, and applications that require high performance.
C++ supports object-oriented programming, generic programming, and low-level memory manipulation.
Examples of software developed using C++ include operating systems like Windows, game engines like Unreal Engine, a...read more
Q55. what is java and its use case
Java is a popular programming language used for developing a wide range of applications.
Java is platform-independent, meaning it can run on any device with a Java Virtual Machine (JVM)
It is used for developing web applications, mobile apps, desktop applications, and enterprise software
Java is known for its security features and scalability
Examples of Java-based applications include Android apps, online banking systems, and e-commerce websites
Q56. what is spring? and features? importance
Spring is a popular Java framework for building web applications and microservices.
Spring provides a comprehensive programming and configuration model for modern Java-based enterprise applications.
It offers features like dependency injection, aspect-oriented programming, and transaction management.
Spring Boot is a popular extension of the framework that simplifies the process of creating standalone, production-grade Spring-based applications.
Spring is important because it hel...read more
Q57. Remove K Corner Elements - Problem Statement
Given an array "arr" consisting of "N" integer elements, your task is to remove "K" elements from the beginning or the end of the array. You must return the maximum ...read more
Given an array, remove K elements from beginning or end to maximize sum of remaining elements.
Iterate through all possible combinations of removing K elements from beginning and end
Calculate sum of remaining elements for each combination
Return the maximum sum obtained
Q58. Minimum Time To Solve The Problems
Given 'N' subjects, each containing a certain number of problems, and 'K' friends, assign subjects to friends such that each subject goes to exactly one friend, maintaining co...read more
Assign subjects to friends to minimize maximum workload, find minimum time for most loaded friend.
Sort subjects in descending order
Assign subjects to friends one by one until all subjects are assigned
The maximum workload will be the sum of problems assigned to the friend with the most problems
Return the maximum workload as the minimum time required
Q59. Shortest Path in an Unweighted Graph
The city of Ninjaland is represented as an unweighted graph with houses and roads. There are 'N' houses numbered 1 to 'N', connected by 'M' bidirectional roads. A road conne...read more
Implement a function to find the shortest path in an unweighted graph from house 'S' to house 'T'.
Use Breadth First Search (BFS) algorithm to find the shortest path in an unweighted graph.
Create a queue to store the current house and its neighbors, and a visited set to keep track of visited houses.
Start BFS from house 'S' and stop when reaching house 'T'.
Return the path from 'S' to 'T' once 'T' is reached.
If multiple shortest paths exist, any one can be returned.
Example: For ...read more
Q60. Sum of LCM Problem Statement
Given an integer 'N', calculate and print the sum of the least common multiples (LCM) for each integer from 1 to N with N.
The sum is represented as:LCM(1, N) + LCM(2, N) + ... + LC...read more
Calculate and print the sum of least common multiples (LCM) for each integer from 1 to N with N.
Iterate from 1 to N and calculate LCM of each number with N
Sum up all the calculated LCMs to get the final result
Implement a function to calculate LCM of two numbers
Q61. Sort an array without inbuilt methods
Sorting an array of strings without using inbuilt methods
Use a sorting algorithm like bubble sort, selection sort, or insertion sort
Compare each element with the next one and swap if necessary
Repeat the process until the array is sorted
Q62. Find All Anagrams Problem Statement
Given a string STR and a non-empty string PTR, identify all the starting indices of anagrams of PTR within STR.
Explanation:
An anagram of a string is another string that can...read more
Q63. What is the javascript
JavaScript is a programming language used for creating interactive web pages and web applications.
JavaScript is a high-level, interpreted language.
It is primarily used for client-side scripting.
JavaScript can be embedded directly into HTML pages.
It provides dynamic functionality and interactivity to websites.
Common uses include form validation, DOM manipulation, and AJAX requests.
Q64. java8 is why so popular?
Java8 is popular due to its new features like lambda expressions, streams, and functional interfaces.
Lambda expressions provide concise code and simplify functional programming.
Streams allow for efficient processing of large data sets.
Functional interfaces enable the use of lambda expressions.
Java8 also introduced new APIs like Optional and Date/Time API.
Java8 is backward compatible with previous versions of Java.
Java8 is widely used in enterprise applications and big data pr...read more
Q65. what is linked list
A linked list is a linear data structure where elements are stored in nodes that have a reference to the next node in the sequence.
Consists of nodes connected by pointers
Does not have a fixed size like arrays
Allows for efficient insertion and deletion operations
Example: Singly linked list, Doubly linked list
Q66. Minimum Removals Problem Statement
Given an integer array ARR
of size N
and an integer K
, determine the minimum number of elements that need to be removed so that the difference between the maximum and minimum ...read more
Q67. Distance Between Two Nodes in a Binary Tree
Given a binary tree and the values of two distinct nodes, determine the distance between these two nodes in the tree. The distance is defined as the minimum number of...read more
Q68. Maximum Sum Path from Leaf to Root Problem
You are tasked with finding the path from a leaf node to the root node in a binary tree, such that this path has the maximum sum among all root-to-leaf paths.
Input:
T...read more
Find the path from a leaf node to the root node in a binary tree with the maximum sum.
Traverse the binary tree from leaf to root while keeping track of the sum along the path.
Compare the sums of all root-to-leaf paths and return the path with the maximum sum.
Use recursion to traverse the tree efficiently and update the sum as you go.
Consider edge cases like null nodes and negative values in the tree.
Q69. Palindrome String Validation
Determine if a given string 'S' is a palindrome, considering only alphanumeric characters and ignoring spaces and symbols.
Note:
The string 'S' should be evaluated in a case-insensi...read more
Q70. BFS Traversal in a Graph
Given an undirected and disconnected graph G(V, E) where V vertices are numbered from 0 to V-1, and E represents edges, your task is to output the BFS traversal starting from the 0th ve...read more
BFS traversal of an undirected and disconnected graph starting from vertex 0.
Implement BFS algorithm to traverse the graph starting from vertex 0.
Use a queue to keep track of visited nodes and their neighbors.
Ensure to print the nodes in numerical sort order when multiple neighbors are present.
Handle disconnected components by checking for unvisited nodes.
Output the BFS traversal sequence for each test case in a separate line.
Q71. Consecutive Elements
Given an array arr
of N
non-negative integers, determine whether the array consists of consecutive numbers. Return true if they do, and false otherwise.
Input:
The first line of input conta...read more
Q72. Dijkstra's Shortest Path Problem
Given an undirected graph with ‘V’ vertices (labeled 0, 1, ... , V-1) and ‘E’ edges, where each edge has a weight representing the distance between two connected nodes (X, Y).
Y...read more
Dijkstra's algorithm is used to find the shortest path from a source node to all other nodes in a graph with weighted edges.
Implement Dijkstra's algorithm to find the shortest path distances from the source node to all other nodes
Use a priority queue to efficiently select the next node with the shortest distance
Update the distances of neighboring nodes if a shorter path is found
Handle disconnected vertices by assigning a large value (e.g., 2147483647) as the distance
Ensure no...read more
Q73. Delete Leaf Nodes with Value X
Given a binary tree where each node contains an integer value, and an integer X, your task is to delete all leaf nodes that have the value X. Continue to remove newly formed leave...read more
Delete all leaf nodes with value X in a binary tree until no such leaves exist.
Traverse the tree in postorder fashion to delete leaf nodes with value X
Recursively call the function on left and right subtrees
Update the root of the tree after removing leaf nodes with value X
Q74. Binary Strings Without Consecutive 1s Problem Statement
Given an integer K, your task is to generate all binary strings of length K such that there are no consecutive 1s in the string.
This means the binary str...read more
Q75. Maximum Time Problem Statement
You are given a string that represents time in the format hh:mm
. Some of the digits are blank (represented by ‘?’
). Your task is to fill in ‘?’
such that the time represented by t...read more
Given a string representing time with some digits as '?', fill in '?' to get maximum time.
Iterate through each digit of the input string and replace '?' with the maximum possible digit based on the position.
For the first digit (hours), if it is '?', replace it with '2' if the second digit is also '?', else replace it with '1'.
For the second digit (hours), if it is '?', replace it with '3' if the first digit is '2', else replace it with '9'.
For the third digit (minutes), if it...read more
Q76. Convert Binary Tree to Mirror Tree
Convert a given binary tree into its mirror tree, where the left and right children of all non-leaf nodes are interchanged.
Input:
An integer ‘T’ denoting the number of test c...read more
Q77. 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 using binary search.
Use binary search to efficiently find the index of each query integer in the rotated sorted array.
Handle the rotation of the array by finding the pivot point first.
Check which half of the array the query integer falls into based on the pivot point.
Return the index of the query integer if found, else return -1.
Q78. Sum of Bit Difference Among All Pairs Problem Statement
Given an array of integers, determine the sum of bit differences among all possible pairs that can be formed using the elements of the array.
The bit diff...read more
Calculate sum of bit differences among all pairs in an array of integers.
Iterate through all pairs of elements in the array
Convert each pair of elements to binary representation
Count the differing bits in the binary representations
Sum up the differing bits for all pairs to get the final result
Q79. Intersection of Linked List Problem
You are provided with two singly linked lists containing integers, where both lists converge at some node belonging to a third linked list.
Your task is to determine the data...read more
Q80. Ninja and the Bulbs Challenge
Ninja owns an electronic shop and possesses 'N' bulbs. To verify the quality of the bulbs, Ninja performs a unique technique. After 'N' rounds of this process, bulbs that remain on...read more
Determine the number of good quality bulbs remaining after 'N' rounds of a unique technique.
In each round, bulbs are toggled based on their position (e.g. every second bulb, every third bulb, etc.)
At the end of 'N' rounds, count the bulbs that remain on to determine the number of good quality bulbs.
Example: For N = 4, bulbs 1 and 4 remain on, so the output is 2.
Q81. Wildcard Queries Problem Statement
Given a dictionary D
with N
words, each of a fixed length L
and consisting only of lowercase English alphabets, answer Q
queries. Each query consists of a word W
of the same l...read more
Given a dictionary and queries with wildcard characters, determine how many words in the dictionary can match each query.
Iterate through each query and dictionary word to check for matches
Replace '?' with all possible lowercase letters and compare with dictionary words
Count the number of matches for each query
Q82. Problem Statement: Delete Node In A Linked List
Given a singly linked list of integers and a reference to a node, your task is to delete that specific node from the linked list. Each node in the linked list has...read more
Given a singly linked list of integers and a reference to a node, delete the specified node from the linked list.
Traverse the linked list to find the node to be deleted.
Update the pointers to skip over the node to be deleted.
Print the modified linked list after deletion.
Ensure the node to be deleted is not the tail node.
Q83. 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
Find the maximum sum of a contiguous subarray within an array of integers.
Use Kadane's algorithm to find the maximum subarray sum efficiently.
Initialize two variables: maxEndingHere and maxSoFar.
Iterate through the array and update the variables accordingly.
Return the maxSoFar as the result.
Q84. Subset OR Problem Statement
You are given an array/list ARR
of N
positive integers. Your task is to determine the size of the smallest subset that achieves the maximum possible OR value among all subsets.
Input...read more
Find the size of the smallest subset with maximum OR value among all subsets of an array of positive integers.
Iterate through all possible subsets of the array
Calculate the OR value for each subset
Track the size of the smallest subset with maximum OR value
Q85. 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
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 up to the specified value.
Initialize the array with base cases and then iterate through the denominations to fill up the array.
The final answer will be in the last cell of the array.
Example: For N=3, D=[1, 2, 3], V=4, the output should be...read more
Q86. Count Distinct Bitwise OR of All Subarrays
Given an array of positive integers, determine the number of distinct values obtained by applying the bitwise OR operation on all possible subarrays.
Explanation:
A su...read more
Count distinct values obtained by applying bitwise OR operation on all possible subarrays of an array of positive integers.
Use a set to store distinct values obtained by bitwise OR operation on all subarrays.
Iterate through all subarrays efficiently to calculate distinct values.
Optimize the solution to handle large input sizes efficiently.
Q87. House Robber Problem Statement
Mr. X is a professional robber with a plan to rob houses arranged in a circular street. Each house has a certain amount of money hidden, separated by a security system that alerts...read more
House Robber problem - determine maximum amount of money to rob without triggering alarm in circular arrangement of houses.
Use dynamic programming to keep track of maximum money robbed at each house.
Consider two cases: robbing the first house and not robbing the first house.
Handle circular arrangement by considering the first and last house separately.
Example: For arr[] = {2, 3, 2}, the output is 3. Mr. X robs house 2.
Example: For arr[] = {1, 2, 3, 1}, the output is 4. Mr. X ...read more
Q88. Rat in a Maze Problem Statement
You need to determine all possible paths for a rat starting at position (0, 0) in a square maze to reach its destination at (N-1, N-1). The maze is represented as an N*N matrix w...read more
Find all possible paths for a rat in a maze to reach its destination, given a matrix representation of the maze.
Use backtracking to explore all possible paths from the starting position to the destination.
Keep track of the current path and explore all possible directions at each step.
Terminate the exploration when reaching the destination and add the path to the result list.
Sort the result list of paths in alphabetical order before returning.
Q89. 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
The problem involves finding the maximum element in each sliding window of size 'K' in an array of integers.
Use a deque to store indices of elements in the current window in decreasing order of their values.
Remove indices that are out of the current window from the front of the deque.
Add the maximum element (at the front of the deque) to the result for each window.
Q90. 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 binary tree is a Binary Search Tree (BST) based on given properties.
Check if the left subtree of a node contains only nodes with data less than the node's data.
Verify if the right subtree of a node contains only nodes with data greater than the node's data.
Ensure that both the left and right subtrees are also binary search trees.
Traverse the tree in level order form to validate the BST properties.
Return true if the binary tree is a BST, otherwise return false.
Q91. Count Palindrome Words in a String
Given a string 'S' consisting of words, your task is to determine the number of palindrome words within 'S'. A word is considered a palindrome if it reads the same backward as...read more
Count the number of palindrome words in a given string.
Split the string into words using whitespace as delimiter.
Check each word if it is a palindrome by comparing it with its reverse.
Increment a counter for each palindrome word found.
Output the final count of palindrome words for each test case.
Q92. Sudoku Solver
Given a 9x9 Sudoku board, your task is to fill the empty slots and return the completed Sudoku solution.
A Sudoku is a grid composed of nine 3x3 smaller grids. The challenge is to fill in the numb...read more
Implement a Sudoku solver for a 9x9 grid with constraints on row, column, and 3x3 grid.
Create a recursive function to solve the Sudoku puzzle by trying out different numbers in empty slots.
Use backtracking to backtrack and try different numbers if a conflict is encountered.
Ensure each number appears only once in each row, column, and 3x3 grid.
Implement a function to check if a number can be placed in a particular position based on Sudoku rules.
Test the solver with different S...read more
Q93. 6.What are local variables and global variables in Python? 7.When to use a tuple vs list vs dictionary in Python? 8.Explain some benefits of Python 9.What is Lambda Functions in Python? 10.What is a Negative In...
read moreLocal variables are variables that are defined within a function and can only be accessed within that function. Global variables are variables that are defined outside of any function and can be accessed throughout the program.
Local variables are created when a function is called and destroyed when the function completes.
Global variables can be accessed and modified by any function in the program.
Using local variables helps in encapsulation and prevents naming conflicts.
Globa...read more
Q94. how can increase immediately sales or marketing figure of a particular company
To increase sales or marketing figures immediately, focus on targeted advertising, offering promotions, improving customer experience, and leveraging social media.
Implement targeted advertising campaigns to reach the right audience
Offer promotions or discounts to attract new customers and incentivize purchases
Improve customer experience through excellent service, personalized interactions, and efficient processes
Leverage social media platforms to engage with customers, create...read more
Q95. tell me about different types of graph..
There are various types of graphs used in data visualization, such as bar graphs, line graphs, pie charts, scatter plots, and histograms.
Bar graph - used to compare different categories
Line graph - shows trends over time
Pie chart - displays parts of a whole
Scatter plot - shows relationship between two variables
Histogram - displays distribution of data
Q96. 11.What is the namespace in Python? 12.What is a dictionary in Python? 13.What is type conversion in Python? 14.What is the difference between Python Arrays and lists? 15.What are functions in Python?
Answers to common Python interview questions.
Namespace is a container for storing variables and functions.
Dictionary is a collection of key-value pairs.
Type conversion is the process of converting one data type to another.
Arrays are homogeneous while lists are heterogeneous.
Functions are blocks of code that perform a specific task.
Q97. 1. What is Python? 2. What Are Python Advantages? 3. Why do you we use in python Function? 4. What is the break Statement? 5. What is tuple in python?
Python is a high-level, interpreted programming language known for its simplicity, readability, and versatility.
Python is used for web development, data analysis, artificial intelligence, and more.
Advantages of Python include its ease of use, large standard library, and community support.
Functions in Python are used to group related code and make it reusable.
The break statement is used to exit a loop prematurely.
A tuple is an ordered, immutable collection of elements.
Q98. difference between ordered and unordered map
Ordered map maintains the order of insertion while unordered map does not guarantee any specific order.
Ordered map: elements are stored in the order they were inserted
Unordered map: elements are stored in an unspecified order for faster access
Example: std::map vs std::unordered_map in C++
Q99. Explain difference between coding and programming?
Coding is the process of writing instructions in a specific programming language, while programming involves the entire process of designing, writing, testing, and maintaining code.
Coding is the act of translating a problem into a language that a computer can understand.
Programming involves planning, designing, implementing, and testing a solution to a problem.
Coding is a subset of programming, focusing on the actual writing of code.
Programming encompasses a broader range of ...read more
Q100. How to make profit in the company
To make profit in a company, focus on increasing revenue and reducing expenses.
Increase sales by expanding customer base or introducing new products/services
Reduce costs by optimizing operations and negotiating better deals with suppliers
Implement cost-cutting measures such as reducing waste and improving efficiency
Invest in research and development to stay ahead of competitors
Consider mergers and acquisitions to increase market share and diversify revenue streams
More about working at Google







Top HR Questions asked in Google for Freshers
Interview Process at Google for Freshers

Top Interview Questions from Similar Companies






Reviews
Interviews
Salaries
Users/Month