0% found this document useful (0 votes)
8 views15 pages

Questions

SDE interview questions

Uploaded by

prateek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views15 pages

Questions

SDE interview questions

Uploaded by

prateek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

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

// Iterate through the string and count occurrences of each


character
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
count[ch]++;
}

// Find the character with the maximum occurrence


char maxChar = 0;
int maxCount = 0;
for (int i = 0; i < count.length; i++) {
if (count[i] > maxCount) {
maxCount = count[i];
maxChar = (char) i;
}
}
System.out.println(count[1]);
return maxChar;
}

public static void main(String[] args) {


String str = "hello world";
char maxOccurrenceChar = findMaxOccurrenceCharacter(str);
System.out.println("Character with maximum occurrence: " +
maxOccurrenceChar);
}
}

USING HASHMAP

import java.util.HashMap;
import java.util.Map;

public class MaxOccurrenceCharacterUsingHashMap {

public static char findMaxOccurrenceChar(String str) {


// Create a hashmap to store character counts
Map<Character, Integer> charCounts = new HashMap<>();

// Iterate through the string and count occurrences of each


character
for (char ch : str.toCharArray()) {
charCounts.put(ch, charCounts.getOrDefault(ch, 0) + 1);
}

// Find the character with the maximum occurrence


char maxChar = '\0'; // Default value if string is empty
int maxCount = Integer.MIN_VALUE;
for (Map.Entry<Character, Integer> entry : charCounts.entrySet())
{
if (entry.getValue() > maxCount) {
maxChar = entry.getKey();
maxCount = entry.getValue();
}
}

return maxChar;
}

public static void main(String[] args) {


String str = "hello world";
char maxChar = findMaxOccurrenceChar(str);
System.out.println("Character with maximum occurrence: " +
maxChar);
}
}
Q. I have an array that has some elements. Find the pair of integers whose sum is equal to
a given number.
{1,3,4,19,6,4,5}, sum=11. Give the best time complexity.

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?

Q. Which other DPs have you worked on?

Q. Aware of the Chain of Responsibility?

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. What is the difference between creational and behavioural design patterns?

Q. Scopes in Spring Bean?

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 overriding in the same class? No

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 Inheritance and Association?

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.

Q. Overloading concept question?


Q. Serialization deSerialization

Synchronous

Inner class

Q. Have you heard about Type promotion?

Q. Try{
Throw new customException;
} catch(Exception t){
Throw new nullPointer;
} finally(){
Throw new illegalArgument;
}
output of the function will be???

Q. What is the cloneable interface? Types (Shallow or Deep)?

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. SOLID? What is Lishkov? Dependency Inversion?

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 underlying Data structure of LinkedList?

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. Internal working of hashmap?

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. FS (fail-safe) vs FF(fail-fast)? Where do we use iterators?

Q. Marker Interface

Q. There is a change in Hashmap in Java 8 for order of N worst case scenario?

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. what is tree set and sorted set?

Q. Generics – What are they? Write one Generic method to add any type of method. Type
Erasure?

Q. Name of a few features added in Java 8.

● Lambda Expressions: Lambda expressions provide a concise way to represent anonymous


functions, enabling functional programming paradigms in Java.
● Stream API: The Stream API provides a fluent and functional approach to processing collections
of data. It allows for efficient and parallelized processing of elements, making it easier to work
with collections in Java.
● Default Methods (Virtual Extension Methods): Default methods allow interfaces to have
concrete methods with default implementations. This feature enables backward compatibility for
existing interfaces and facilitates the evolution of interfaces without breaking existing
implementations.
● Functional Interfaces: Functional interfaces are interfaces that have exactly one abstract
method. They can be annotated with the @FunctionalInterface annotation, and they are used
extensively with lambda expressions and the Stream API.
● Optional: The Optional class is a container object that may or may not contain a non-null value. It
helps prevent NullPointerExceptions by providing a more expressive way to handle potentially
null values.
● Date and Time API: The java.time package introduced in Java 8 provides a comprehensive and
immutable set of classes for representing dates, times, time zones, durations, and periods. It
addresses the shortcomings of the previous Date and Calendar classes.
● CompletableFuture: The CompletableFuture class is an enhanced version of the Future
interface, providing a powerful way to represent asynchronous computations and handle their
results using fluent APIs and callback mechanisms.
● Method References: Method references provide a shorthand syntax for referring to methods or
constructors of classes. They can be used in place of lambda expressions in certain contexts,
making the code more concise and readable.
● Parallel Array Sorting: The Arrays class introduced parallel sorting methods (parallelSort) for
arrays, allowing for more efficient sorting of large arrays by utilizing multiple CPU cores.
● Nashorn JavaScript Engine: Java 8 includes the Nashorn JavaScript engine, which provides a
lightweight and high-performance JavaScript runtime environment for Java applications
Q. What is the method name in Predicate? (Functional Interface Question)

Q. Create one Predicate object via Lambda.


import java.util.function.Predicate;
public class PredicateExample {
public static void main(String[] args) {
// Create a Predicate to test if a number is greater than 10
Predicate<Integer> isGreaterThan10 = num -> num > 10;
// Test the Predicate with some values
System.out.println(isGreaterThan10.test(5)); // Output: false
System.out.println(isGreaterThan10.test(15)); // Output: true
}
}

Q. Create an object of Function via Lambda.


import java.util.function.Function;
public class FunctionExample {
public static void main(String[] args) {
// Create a Function to double the input number
Function<Integer, Integer> doubleFunction = num -> num * 2;
// Apply the Function to some values
System.out.println(doubleFunction.apply(5)); // Output: 10
System.out.println(doubleFunction.apply(10)); // Output: 20
}
}

Q. What are intermediate and terminal operations in Streams?

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:

● map: Transforms each element of the stream using a given function.


● filter: Filters the elements of the stream based on a given predicate.
● sorted: Sorts the elements of the stream based on a comparator.
● distinct: Removes duplicate elements from the stream.
● limit: Limits the size of the stream to a specified number of elements.
● skip: Skips a specified number of elements from the beginning of the stream.

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:

● forEach: Performs an action for each element of the stream.


● collect: Collects the elements of the stream into a collection or other data structure.
● reduce: Performs a reduction operation on the elements of the stream, resulting in a single value.
● count: Returns the number of elements in the stream.
● anyMatch, allMatch, noneMatch: Checks if any, all, or none of the elements of the stream
match a given predicate.
● findAny, findFirst: Returns an optional containing any or the first element of the stream,
respectively.

Q. What are parallel streams?

Q. What are some predefined Functional Interfaces – Java 8 has given some new Functional
Interfaces to support functional programming.

Q. What is method reference in Lambda?


Method references in Java Lambda expressions provide a shorthand syntax for calling methods.
They allow you to refer to methods or constructors without invoking them explicitly, making the
code more concise and readable.

Q. What is the method name in the supplier functional interface get()? The abstract method
name?

public class SupplierExample {


public static void main(String[] args) {
// Define a supplier that generates a random integer
Supplier<Integer> randomSupplier = () -> (int) (Math.random() * 100);
// Get a random integer from the supplier
int randomNumber = randomSupplier.get();
// Print the generated random number
System.out.println("Random number: " + randomNumber);
}
}

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);
}
}

Q. How can you convert the array into Stream? Arrays.stream(array);

Q. Why do we call Streams as lazy?

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;

public static void main(String[] args) {


Thread t1 = new Thread(Main::printEven);
Thread t2 = new Thread(Main::printOdd);

t1.start();
t2.start();
}

private static void printEven() {


while (count <= MAX_COUNT) {
synchronized (lock) {
while (count % 2 != 0) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()
+ ": " + count++);
lock.notify();
}
}
}

private static void printOdd() {


while (count <= MAX_COUNT) {
synchronized (lock) {
while (count % 2 == 0) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()
+ ": " + count++);
lock.notify();
}
}
}
}

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. What CAP Theorem do Mongo and SQL follow?

Q. where and having difference

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

SELECT MAX(salary) AS third_largest_salary


FROM employees
WHERE salary < (SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary)
FROM employees)
);

Q. Procedure, View, Transaction and Rollback in Database?

Q. What is cascading in JPA?

Q. Any JVM Profiler?


Q. Different types of Garbage Collector in Java 8? Which one is default and how can we change
it?

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. Unit and Integration testing?

Q. What are REST principles?

Q. Difference between @controller and @restcontroller?

Q. Exexuters

Q. How are you managing pagination in REST?

Q. Any Microservice Design pattern – SAGA, CB, CQRS, Service Mesh?

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?

Q. Have you heard DDoS(Distributed Denial of Service) attack?

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.

Coding Question Idea

1. Write a function to return the longest even-length word in a sentence.


2. You have to distribute N bananas equally among some monkeys according to the
following conditions:
● You can choose the number of monkeys that receive bananas.
● Each monkey should get more than one banana.
● One monkey cannot receive all the bananas.
● All the N bananas must be distributed.
● Each monkey can only receive an integral number of bananas.

Write a program to determine whether the bananas can be equally distributed among the
monkeys. There will be bonus marks for optimizing the solution.

Input format N bananas to be distributed.


Output format
Return true or false depending upon the result.
Examples
N=2
2 bananas cannot be distributed among group of any size. Suppose we take a group of
size 1 then one monkey takes all the bananas. If we take a group of size 2 each monkey
will only 1 banana which violates the rule of distribution.
N=4
4 can be equally distributed among 2 monkeys each one getting 2 bananas.

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

fuel : [1, 2, 3, 4, 5, 6],


cost: [3, 4, 15, 1, 5, 20]

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

S1 become → acrfg; S2 becomes → acrfg


Output: true

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

Array = [12, 3, 1, 2, -6, 5, -8, 6]


targetSum = 0

Sample Output

[ [-8, 2,6 ], [-8, 3, 5], [-6, 1, 5]]

You might also like