Questions
Questions
Q. How do you communicate within your Microservice(MS)? Let’s say you have MS A and MS B,
how do they interact? Are they independent?
Each microservice has its own instance and process. Therefore, services must interact using an
inter-service communication protocols like HTTP, gRPC or message brokers (Advance
Messaging Queue Protocol) protocol.
HTTP/REST API
Messaging Queues/Brokers
gRPC (google Remote Procedure Call)
Service Mesh
Q. There is a string. Find the character that has the maximum occurrence.
USING ASCII:
public class MaxOccurrenceCharacter {
public static char findMaxOccurrenceCharacter(String str) {
// Create an array to store the count of each character (assuming
ASCII characters)
int[] count = new int[256]; // Assuming ASCII characters
USING HASHMAP
import java.util.HashMap;
import java.util.Map;
return maxChar;
}
import java.util.*;
public class FindPairWithSum {
/**
* Time Complexity in O(nlog(n))
* due to sort
*/
public static void findPairsWithSum(int[] arr, int sum) {
Arrays.sort(arr); // Sort the array (assuming it's not already
sorted)
int left = 0; // Initialize left pointer
int right = arr.length - 1; // Initialize right pointer
while (left < right) {
int currentSum = arr[left] + arr[right];
if (currentSum == sum) {
System.out.println("Pair found: " + arr[left] + ", " +
arr[right]);
left++; // Move left pointer forward
right--; // Move right pointer backward
} else if (currentSum < sum) {
left++; // Move left pointer forward
} else {
right--; // Move right pointer backward
}
}
}
/**
* Time Complexity in O(n)
*/
public static void findPairsWithSumUsingSet(int[] arr, int sum) {
Set<Integer> complements = new HashSet<>();
for (int num : arr) {
int complement = sum - num;
if (complements.contains(complement)) {
System.out.println("Pair found: " + num + ", " +
complement);
}
complements.add(num);
}
}
public static void main(String[] args) {
int[] arr = {1, 3, 4, 19, 6, 4, 5};
int sum = 11;
findPairsWithSum(arr, sum);
}
}
Q. Write a Singleton class. Consider it safe from deserialization, reflection and threads. How will
you prevent the creation of multiple objects via Reflection and Cloneable?
The Chain of Responsibility is a behavioural design pattern that allows an object to pass a
request along a chain of handlers. Upon receiving a request, each handler decides either
to process the request or to pass it to the next handler in the chain.
Example: consider an example where we have different levels of technical support for
handling customer queries. Each level of support can handle a certain range of issues,
and if they can't handle it, the query is forwarded to the next level.
Q. How do we handle global exceptions in the spring application? The concept of global
exception handling?
Q. Exception Handling – What is it? What is the parent of all exceptions? (Throwable class) Why
throwable is a class? Noclassdefinitionfound error – When does it come into the picture?
Q. What is Try with Resource? How can you know if this resource can be closed via try? I have to
just transfer my file from one variable to another variable or another class object. Can we use this
try with resources in this scenario?
Q. Can we do method overloading in the same class? Can you do it in a parent-child relationship
(method overloading) – Yes then how will you achieve it?? Yes
Q. What is Association?
Q. What is Polymorphism and its types? Run time and Compile time? We have a static method. If
we override the static method, will it be runtime or compile-time polymorphism? Write pseudo
code for both.
Synchronous
Inner class
Q. Try{
Throw new customException;
} catch(Exception t){
Throw new nullPointer;
} finally(){
Throw new illegalArgument;
}
output of the function will be???
Q. Immutability? Write a custom immutable class? Other than string, what other types are
immutable? What are the parameters?
Q. Custom exceptions? How do you decide that these exceptions should be runtime or
compile-time exceptions?
Q. Jackson library? use case of this Jackson library? let's suppose I have one class. (student
class). We have ID, name and address. Whenever I am converting my Json, I need the address
first, then name and then ID. Can we achieve it?
@JsonPropertyOrder
Q. What is the time complexity to insert an element in Hashmap O(1)? What is the time
complexity to search in hashmap (in best and worst cases) O(1) O(n) due to collision?
Q. I have to insert one custom class in the list. What all you need to consider for this?
Q. You have to insert a custom element in a set, what do you need to consider?
Q. What is the time complexity of a Treemap O(log(n))? What is the underlying DataStructure of
Treemap Red black tree (Self balancing tree)?
Q. Underlying Data Structure of Hashset? HashTable
Q. Marker Interface
HashMap introduced a tree structure (red-black tree) for buckets that exceed a certain
threshold of elements. This threshold was set to 8 in Java 8. When the number of elements
in a bucket exceeds this threshold, the elements in that bucket are stored in a balanced
tree instead of a linked list.
Q. Generics – What are they? Write one Generic method to add any type of method. Type
Erasure?
Intermediate Operations:
Intermediate operations are operations that transform or manipulate the elements of a stream.
These operations are lazy, meaning they do not perform any processing until a terminal operation
is invoked. Intermediate operations return a new stream, allowing for method chaining. Some
common intermediate operations include:
Terminal Operations:
Terminal operations are operations that produce a result or side-effect. When a terminal operation
is invoked, the intermediate operations are executed, and the stream is consumed. Terminal
operations are eagerly executed, meaning they trigger the processing of the stream. Once a
terminal operation is invoked, the stream is closed, and it cannot be reused. Some common
terminal operations include:
Q. What are some predefined Functional Interfaces – Java 8 has given some new Functional
Interfaces to support functional programming.
Q. What is the method name in the supplier functional interface get()? The abstract method
name?
Q. Array of integers – List the square of all the elements that are less then 10.I need it in a
List using streams.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(4, 10, 3, 15, 22, 7,
9);
List<Integer> squaresOfNumbersLessThan10 = numbers.stream()
.filter(n -> n < 10) // Filter elements less than 10
.map(n -> n * n) // Square each element
.collect(Collectors.toList());
System.out.println("Square of all elements less than 10: " +
squaresOfNumbersLessThan10);
}
}
Multi Threading
Q. Different types of Monitor and Locks?
Q. Dead locks and how to resolve dead locks
Q. Reentrant Lock?
Q. Which Executors have you worked on? Explain type of Executors in Java.
Q. Why do we use scheduled Thread Pools?
Q. Difference between Sleep and Wait methods?
Q. Countdown Latch?
Q. Semaphores?
Q. In which scenario we should use notify and notifyall?
Q. Difference between Sleep and Yield?
Q. What are the different states of a Thread?
Q. Print 1-100. I have two threads. T1 will print even numbers and T2 will print odd numbers.
How?
Q. Callable and runnable interface
public class Main {
private static final Object lock = new Object();
private static int count = 1;
private static final int MAX_COUNT = 100;
t1.start();
t2.start();
}
Kafka
Q. Kafka – You have one consumer group, one topics and one partition only. Now in your
application, you have four instances that are using the same topic. Which instances will have
access to that topic and which one will not have access?
Q. Let’s say you have ten partitions and in the consumer group you have only one instance, now
what?
Q. Give me some property names that you use while connecting to Kafka.
Q. Any Message Broker? What are all the exchanges available in RabbitMQ?
Databases
Q. Indexing? Disadvantages of Indexing?
disadvantage : increased storage overhead, slow write operation, complexity
Q. Write a query to find the third largest salary from an employee table.
SELECT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 2;
The problem with the above solution is what if the top 3 are the
same salary
Q. Any JVM-related config like setting up memory, and heap size? Different memory areas in
JVM?
Q. Explain the current application and Layering. Which Source control do you use?
Q. Exexuters
Q. Caching?
Q. Let’s say I have one GET API. We developed it and it is working fine. After one or two years,
there are some issues like lagging in the network. It is being reported that your API is lagging,
and is taking too much time. What might be the issue?
Several factors could contribute to the lagging performance of a GET API after it has been
working fine for some time. Here are some potential issues to investigate:
● Increased Data Volume: Over time, the amount of data processed by the API may have
increased significantly, leading to longer processing times. Review the volume of data being
processed and optimize the API to handle larger datasets efficiently.
● Database Performance: If the API relies on a database backend, deteriorating database
performance could impact API response times. Check for database indexing, query optimization,
and database server resource utilization to identify potential bottlenecks.
● Network Latency: Network latency can increase over time due to changes in network
infrastructure, increased network traffic, or network congestion. Monitor network performance
metrics such as latency, packet loss, and throughput to identify any issues affecting API
communication.
● Server Resource Constraints: The server hosting the API may be experiencing resource
constraints such as high CPU usage, memory exhaustion, or disk I/O bottlenecks. Monitor server
resource utilization and consider scaling up resources or optimizing resource usage to improve
API performance.
● Code Degradation: Changes or updates to the API codebase over time may introduce
inefficiencies, memory leaks, or performance bottlenecks. Perform code reviews, profiling, and
performance testing to identify and address any code degradation issues.
● External Dependencies: External dependencies such as third-party APIs, services, or
integrations may experience performance issues or downtime, affecting the overall performance
of the API. Monitor dependencies and implement retries, caching, or fallback mechanisms to
mitigate the impact of external failures.
● Caching Strategy: Inadequate or ineffective caching strategies may result in frequent database
or resource accesses, leading to increased latency. Review caching mechanisms and optimize
cache utilization to reduce the load on backend systems and improve response times.
● Load Balancer Configuration: Improperly configured load balancers or load balancing
algorithms may distribute traffic unevenly across backend servers, causing performance issues.
Review load balancer configurations and adjust settings as needed to evenly distribute traffic and
improve API performance.
● Monitoring and Alerting: Insufficient monitoring and alerting capabilities may delay the detection
and resolution of performance issues. Implement comprehensive monitoring and alerting systems
to proactively identify and address performance degradation in real time.
Q. Have you handled rollback back type of things like let's suppose you're 1 microservice has
processed a few things, and another is getting some error no matter which approach you have
taken. So how you will be rolling back the previous micro service?
Q. I have one method and what I want is I I want to provide method-level security right? I just
want the admin can access this method but not others. How can we achieve it?
@Secured("ROLE_ADMIN")
public void adminOnlyMethod() {
// Method implementation
}
Q. How can you secure the APIs? In OAuth, we have two types of keys – The access key and the
refresh key. Any idea?
Distributed Denial of Service (DDoS) attack is a type of cyber attack where multiple compromised
computer systems, often referred to as bots or zombies, are used to flood a target system or
network with an overwhelming amount of traffic, disrupting its normal operation and making it
unavailable to legitimate users.
To mitigate DDoS attacks, organizations employ various strategies and technologies, such as:
● Traffic Filtering and Scrubbing: Using specialized hardware or cloud-based services to filter out
malicious traffic and allow only legitimate traffic to reach the target.
● Rate Limiting and Throttling: Implementing measures to limit the rate of incoming requests or
connections to prevent overwhelming the target system.
● Content Delivery Networks (CDNs): Distributing content across multiple servers geographically
dispersed to absorb and mitigate DDoS attacks.
● Anomaly Detection Systems: Employing intrusion detection and prevention systems to identify
and block abnormal traffic patterns associated with DDoS attacks.
● Redundancy and Failover: Designing systems with redundant components and failover
mechanisms to maintain service availability during DDoS attacks.
Write a program to determine whether the bananas can be equally distributed among the
monkeys. There will be bonus marks for optimizing the solution.
3. Write a function to find the pair with the maximum product in an array of integers.
4. There are n gas stations along a circular route, where the amount of gas at the ith station
is gas[i]. It takes the cost[i] of gas to travel from ith station to i+1th station. You begin with
an empty tank at any one of these stations. Given two integer array gas and cost, return
the starting index if you can travel around the circuit once in the clockwise direction,
otherwise return -1.
e.g:
fuel : [1, 2, 3, 4, 5], // 4 5 1 2 3
cost: [3, 4, 15, 1, 5] // 1 5 3 4 15
output: 3
4→5→1→2→3→4
fuel: [2,3,4],
cost: [3,4,3]
output: -1
5. [14, 0, 34, 0, 0, 16, 22, 0, 56, 0, 17] shift all zeros at last
Output [14,34,16,22,56,17,0,0,0,0]
6. String S1 = acrd#fg, s2 = acht##rfg → # means pop check if both string are same
e.g.
S1 = ab#c#d → ad
S2 = abc##d → ad
Output: true
7. Find the triplets whose sum is 0;
8. Find the longest substring without repeating any character.
9. Character count.
10. Replace every character in a string with index divisible by 3.
11. Matrix Manipulation. (make whole row column 0 if encounter any cell as 2 in the given all
cell as 1 matrix)
12. Search in the rotated array
13. Parenthesis validation
14. Sort array 0’s 1’s 2’s (Dutch Flag)
15. The subarray sum is equal to the target
16. Max profit stock { 7, 1, 5, 3, 6, 4 }
17. Find the first and last occurrence of the element in a given array.
18. Write a program to find the sum of all the numbers in the alphanumeric string.
19. Delete duplicates in linkedlist 1->2->->5->2->3->null.
20. Two pointers
21. Strings
22. PatternMatching
23. LinkedList
24. Binary Search- Painters Partition..
25. Guess - what's the famous problem solved using Kadene's Algo'...
26. A valid IPv4 address is an IP in the form "x1.x2.x3.x4" where 0 <= xi <= 255 and xi cannot contain
leading zeros.
For example, "192.168.1.1" and "192.168.1.0" are valid IPv4 addresses while "192.168.01.1",
"192.168.1.00", and "192.168@1.1" are invalid IPv4 addresses.
27. Write a function that takes in a non-empty array of distinct integers and an integer
representing a target sum. The function should find all triplets in the array that sum up to
the target sum and return a two-dimensional array of all these triplets. The numbers in
each triplet should be ordered in ascending order, and the triplets themselves should be
ordered in ascending order with respect to the numbers they hold.
Sample Input
Sample Output