Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views8 pages

Interview Questions

Uploaded by

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

Interview Questions

Uploaded by

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

Problem: First and Last Occurrence of an Element in a

Sorted Array
📝 Problem Statement

Given a sorted array of integers and a target element, find the first and last position of the
target in the array using binary search.

 If the element is not present, return [-1, -1].


 Solve it in O(log n) time complexity.

📌 Example 1

Input

java
CopyEdit
nums = [5, 7, 7, 8, 8, 10]
target = 8

Output

java
CopyEdit
[3, 4]

Explanation

 8 first appears at index 3.


 8 last appears at index 4.

📌 Example 2

Input

java
CopyEdit
nums = [5, 7, 7, 8, 8, 10]
target = 6

Output

java
CopyEdit
[-1, -1]

Explanation
 6 is not present in the array.

📌 Example 3

Input

java
CopyEdit
nums = []
target = 0

Output

java
CopyEdit
[-1, -1]

Explanation

 The array is empty, so return [-1, -1].

🔹 Solution Approach (Using Binary Search)


🛠 Steps

1. Find First Occurrence using Binary Search


o Search for target in the array.
o If found, continue searching left to find the first occurrence.
2. Find Last Occurrence using Binary Search
o Search for target again.
o If found, continue searching right to find the last occurrence.

1. What are the key features of Java 17?

Answer:

Java 17 is an LTS release with several improvements:

 Sealed Classes (Finalized in JEP 409): Restrict class hierarchies.


 Pattern Matching for Switch (Preview - JEP 406): Enhances switch to work with
patterns.
 Strongly Encapsulated JDK Internals (JEP 403): Blocks deep reflection on internal
APIs.
 New macOS Rendering Pipeline (JEP 382): Uses Metal instead of OpenGL.
 Removal of RMI Activation System.
 New APIs like RandomGenerator.

6. How does Spring Boot handle dependency injection?

10. How does Spring Boot handle Caching?

Answer:

Spring Boot supports caching via @Cacheable, @CachePut, and @CacheEvict:

15. What is Circuit Breaker, and how does it work in Spring Boot?

Answer:

Circuit Breaker prevents failures from cascading in microservices.


Spring Boot uses Resilience4j:

java
CopyEdit
@CircuitBreaker(name = "orderService", fallbackMethod = "fallbackOrder")
public String getOrder() {
return restTemplate.getForObject("http://ORDER-SERVICE/orders",
String.class);
}

public String fallbackOrder(Exception e) {


return "Fallback order response";
}

4. What is the difference between Optional.of(), Optional.ofNullable(), and


Optional.empty()?

Answer:

 Optional.of(value) → Throws NullPointerException if value is null.


 Optional.ofNullable(value) → Returns empty if value is null.
 Optional.empty() → Returns an empty optional.
6. What are Spring Profiles and how do you use them?

9. How do you handle soft deletes in JPA?

Answer:

Soft deletes allow "deleting" a record without actually removing it from the database.

Approach:

 Add a deleted flag in the entity:

java
CopyEdit
@Entity
@SQLDelete(sql = "UPDATE users SET deleted = true WHERE id = ?")
@Where(clause = "deleted = false")
public class User {
@Id
private Long id;

private boolean deleted = false;


}

To fetch the 3rd highest mark in a subject, you can use different SQL approaches.

Method 1: Using LIMIT with OFFSET (MySQL, PostgreSQL)


sql
CopyEdit
SELECT DISTINCT marks
FROM students
WHERE subject = 'Math'
ORDER BY marks DESC
LIMIT 1 OFFSET 2;

Method 3: Using DENSE_RANK() (Best for handling duplicate marks)


sql
CopyEdit
SELECT marks
FROM (
SELECT marks, DENSE_RANK() OVER (ORDER BY marks DESC) AS rnk
FROM students
WHERE subject = 'Math'
) ranked
WHERE rnk = 3;

❓ Find employees who earn more than the company’s average salary.

sql
CopyEdit
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

💡 Concepts Covered: Subquery, Aggregation

❓ Rank employees by salary in each department.

sql
CopyEdit
SELECT name, department_id, salary,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS
salary_rank
FROM employees;

💡 Concepts Covered: RANK(), PARTITION BY

❓ Find duplicate records in a table.

sql
CopyEdit
SELECT email, COUNT(*)
FROM users
GROUP BY email
HAVING COUNT(*) > 1;

💡 Concepts Covered: GROUP BY, HAVING

❓ Find the department with the highest average salary.

sql
CopyEdit
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
ORDER BY avg_salary DESC
LIMIT 1;

💡 Concepts Covered: AVG(), GROUP BY, ORDER BY, LIMIT

Scenario-Based Questions
1. High-Concurrency Scenario:
o You have a Spring Boot REST API with high concurrent requests. How do
you optimize performance?
o How do you manage thread pools in Spring Boot?
2. Microservices Communication:
o How do you ensure consistency between two microservices without a
distributed transaction?
o How does Event-Driven Architecture help in microservices?
3. Database Scaling & Optimization:
o Your database queries are slowing down. How do you identify and fix
bottlenecks?
o How do you implement read replicas in Spring Boot for database scalability?
4. Security Hardening:
o How do you secure REST APIs in Spring Boot?
o How do you prevent SQL injection and XXE attacks?
5. Logging & Monitoring:
o How do you set up distributed logging in a Spring Boot microservices
architecture?
o How does Prometheus & Grafana integrate with Spring Boot for
monitoring?

1. What are idempotent methods in REST APIs?

Answer:
Idempotent methods ensure that multiple identical requests have the same effect as a single
request.

Idempotent HTTP methods: GET, PUT, DELETE, HEAD, OPTIONS

Example:

 Sending multiple PUT /users/123 requests with the same payload will update the
user, but the outcome remains the same.
 DELETE /users/123 is idempotent because deleting an already deleted user has no
additional effect.

8. How do you optimize REST APIs for high performance?

Answer:

1. Use Caching:
o Cache-Control: max-age=3600, public
o Implement ETag for response validation
2. Use Asynchronous Processing:
o Move heavy operations to message queues (Kafka, RabbitMQ)
o Use WebSockets or Event-Driven APIs
3. Minimize Payload Size:
o Use GZIP compression
o Implement field filtering (/users?fields=id,name)
4. Use Database Indexing & Optimization
o Use proper indexes (B-tree, Hash Indexes)
o Optimize JOIN queries
5. Enable Pagination for Large Datasets
o Instead of GET /users returning thousands of records, use ?page=1&size=50

9. How would you scale a REST API?

Answer:
✅ Load Balancing: Distribute traffic using NGINX, AWS ALB, HAProxy
✅ Horizontal Scaling: Deploy API servers across multiple instances
✅ Database Optimization: Use Read Replicas and Sharding
✅ Caching: Implement Redis or Memcached for frequently accessed data
✅ Asynchronous Processing: Use Kafka, RabbitMQ for background jobs
✅ CDN (Content Delivery Network): Cache static content for fast retrieval

4. What are some best practices for designing REST APIs?

Answer:
✅ Use proper HTTP methods (GET, POST, PUT, DELETE, PATCH)
✅ Use plural nouns for resources (/users instead of /user)
✅ Use meaningful status codes (e.g., 200 OK, 201 Created, 400 Bad Request, 404 Not
Found, 500 Internal Server Error)
✅ Provide pagination for large responses (/users?page=2&size=20)
✅ Use authentication & authorization (OAuth2, JWT)
✅ Enable caching for performance improvement
Ask about design patterns

1. Singleton
2. Builder
3. Factory
4. Strategy
5. Decorator
6. Façade
7. Observer

🎯 Problem Statement (Simplified Scope)


Design a system to:

 Browse movies, cinemas, and showtimes


 View available seats for a show
 Book tickets
 Support payment module (simplified)
 Prevent double-booking

Consider the following employee table :

Name Age Department Salary


Ramesh 20 Finance 50, 000
Deep 25 Sales 30, 000
Suresh 22 Finance 50000
Ram 28 Finance 20, 000
Pradeep 22 Sales 20, 000

Find average salary of employees for each department and order employees within a
department by age

You might also like