Interview guides · Cognizant
Cognizant Software Engineer Interview Guide
Cognizant Software Engineer interview guide: OOP, SQL, coding and Spring/React questions candidates report, a 3-round loop overview and a 7-day plan.
The 60-second brief
Cognizant is described by candidates as a global consulting and technology services provider. Its Software Engineers build and maintain enterprise software for client companies in industries such as healthcare, financial services, retail and manufacturing. Reported back-end work uses Java, Python or .NET, front-end work uses React or Angular, and deployments run on AWS or Azure. Depending on the track, the day-to-day can be full-stack microservices, API integrations, data engineering pipelines or managed services for existing enterprise applications, usually alongside client technical leads, project managers and quality engineers.
This guide is for candidates applying to Cognizant as a Software Engineer, whether through a campus programme (GenC, GenC Pro, GenC Next) or as a lateral hire with prior enterprise experience. It covers the three reported rounds, the questions candidates report on OOP, coding, SQL, web frameworks and project experience, and a plan for rehearsing them. It is not a guide to the Data Scientist or Machine Learning Engineer loops.
Candidates report three rounds over roughly three to five weeks: a Phone Screening, Technical Assessments covering coding and domain knowledge, and Final Interviews that cover technical ability, communication and fit.
Focus areas
- Java
- SQL
- Python
Overview
The role is enterprise delivery work: building, testing and maintaining software that a client's business runs on, in a language such as Java, Python or C#, with a relational database underneath and, on some tracks, Spring Boot, Django, Flask, .NET Core, React or Angular on top. The reported questions match that shape. Most of them are fundamentals that you can answer precisely if you have rehearsed them: the OOP pillars, overloading versus overriding, how exceptions and the finally block behave, list versus tuple versus set, short string and array programs, and everyday SQL.
Candidates describe several entry points. Campus programmes (GenC, GenC Pro, GenC Next) are reported to lean on core OOP, basic programming logic, standard SQL and spoken English. Lateral hires with two or more years of experience are reported to get more architecture, microservices and client-scenario questions. Decide which description fits you, then weight your week accordingly: a fresher should drill the fundamentals until they are automatic, an experienced engineer should add the framework and resilience questions (Spring versus Spring Boot, the Circuit Breaker pattern, Docker versus Kubernetes).
The 25 reported questions fall into five groups: core programming and OOP, coding challenges, SQL, web and cloud frameworks, and project or behavioral prompts. A reliable shape for the technical ones is definition, contrast, tiny code example, then the trap. For example, for the final, finally and finalize question you name what each one is (a modifier, a block, a method), then show a snippet in which finally runs after a return. Practise saying that out loud, because candidates report that explaining your logic while you write is part of the loop.
Two things apply to every round. First, communication: candidates report an early voice-based assessment and later live conversations with technical and managerial panels, so clear spoken English and a calm, structured delivery matter as much as correct code. Second, your resume: candidates report deep-dive questions on listed projects and technologies, so prepare the project walkthrough with the same care as the algorithms and cut anything you cannot explain.
The Cognizant interview process
Candidates describe three stages, from an initial screen through technical assessments to final interviews; write-ups differ on exact formats, so treat the details below as what is commonly reported.
Phone Screening
Candidates report the Phone Screening as an initial conversation to judge fit. Separate write-ups describe the start of the process as automated assessments in aptitude, logical reasoning and game-based puzzles, plus a voice-based communication check that includes repeating spoken sentences, comprehension and short answers. Treat it as the stage where clear speech and a short, confident introduction count most. Do the voice assessment in a quiet room with a working microphone, and have an answer ready for why you want this company and whether you can relocate or change stack.
What to demonstrate
- Fit for the organization, which is how the stage is described
- Spoken English: clarity, pace and comprehension
- How concisely you introduce your education, skills and projects
How to prepare
- Write and rehearse a two-minute introduction covering education, core language, one or two projects and why Cognizant.
- Practise repeating sentences aloud at a steady pace and answering short spoken prompts with a full sentence, recording yourself once to check clarity.
- Prepare a straight answer to the question about relocating or moving to a different tech stack depending on project needs.
Technical Assessments
Technical Assessments are described as testing both coding skills and domain knowledge. Candidates report data structures, core programming problems, SQL queries and multiple-choice questions on their chosen language track, worked on built-in assessment environments where you write runnable code. This is where the string and array programs (reverse a string, second largest number, palindrome, remove duplicates, XOR swap) and the SQL questions (second highest salary, DELETE versus TRUNCATE versus DROP, joins, GROUP BY and HAVING) are practised. Prepare to write complete, compiling code, not pseudocode.
What to demonstrate
- Working code for fundamental problems on strings, arrays and numbers
- SQL: aggregation, joins, filtering and the second-highest pattern
- Language fundamentals in your chosen track (Java, Python or C#)
- Whether you handle edge cases such as empty input and duplicates
How to prepare
- Solve the reverse-string, second-largest, palindrome, remove-duplicates and XOR-swap problems in your primary language in a plain editor without autocomplete, stating complexity for each.
- Write the second-highest-salary query two ways and the employees-per-department query with GROUP BY and HAVING, and run them against a small table you create.
- Rehearse one-minute answers on final versus finally versus finalize, overloading versus overriding, and list versus tuple versus set, each with a short code example.
Final Interviews
Final Interviews are described as evaluating technical capability, communication skills and cultural fit. Candidates report live technical and managerial interviews, held virtually or in person, covering live coding, SQL and schema work, OOP concepts and a deep dive into resume projects, followed by an HR conversation about location flexibility and compensation. Prepare the project walkthrough in detail, the track-specific framework questions (Spring and Spring Boot, React, Circuit Breaker, Docker and Kubernetes, REST) and the behavioral prompts on deadlines, disagreement and learning new stacks.
What to demonstrate
- Technical depth on the projects listed on your resume
- Live coding and OOP fundamentals under conversation
- Communication of trade-offs and design decisions
- Flexibility on stack and location, as reported for the managerial and HR discussions
How to prepare
- Build a one-page project sheet: your role, the request flow, main tables and keys, libraries used, two design decisions and one bug you fixed.
- Practise the framework questions for your track aloud, for example how dependency injection works in Spring Boot, what the Virtual DOM does in React, and what a Circuit Breaker does when a downstream service fails.
- Write three STAR stories (a deadline change, a technical disagreement, learning a stack quickly) and tie each to a real project from your resume.
Where candidates lose points
Reciting the four OOP pillars as definitions with no code or realistic example
For each of abstraction, encapsulation, inheritance and polymorphism, prepare one small class sketch from a domain you can talk about, such as a banking account hierarchy with a private balance, a base class and an overridden method. Say which pillar each line shows.
Mixing up near-identical pairs: final, finally and finalize, or overloading and overriding
Memorise one sentence each plus a snippet that proves it: finally runs after a return, overloading is resolved at compile time by signature, overriding at runtime by the object's class. Practise saying it without notes.
Writing the string and array programs without edge cases or stated complexity
For second largest, say what happens with fewer than two distinct values or all-equal input. For palindromes, decide case, spaces and negative numbers. Mention that XOR swap on the same variable gives zero. State time and space for each answer.
A second-highest-salary query that breaks on ties or a missing second value, or confusing DELETE, TRUNCATE and DROP
Use DENSE_RANK or a subquery on MAX and say what each returns for ties and when there is no second salary. For DELETE, TRUNCATE and DROP, state row removal versus table definition removal, WHERE support, triggers and rollback behaviour, noting that rollback details differ by database.
A project walkthrough that says "we" throughout and lists technologies you cannot explain
Prepare a one-page sheet with your own modules, the request flow, key tables and one bug you fixed, and remove any resume item you could not defend for two minutes.
Questions & practice
How does exception handling work, and what is the function of the finally block during runtime?
Medium · Core Programming & OOP Concepts
Approach
- Walk through what the runtime does. throw creates an exception object and the stack unwinds frame by frame until a catch matches its type. Catches are checked in order, so the specific type goes before the general one. If nothing matches, the exception reaches the top of the thread, the default handler prints the stack trace and the thread ends.
- finally runs in every path: after normal completion, after a catch, and while an uncaught exception passes through. With try/finally and no catch, finally runs and then the exception keeps propagating. Use it to release locks, connections and file handles.
- Point out the traps: a return in finally replaces the try's return value and silently discards an in-flight exception, and an exception thrown inside finally replaces the original one.
- Java details: checked exceptions must be caught or declared, unchecked ones (RuntimeException, Error) need neither. try-with-resources closes resources in reverse order and attaches close() failures as suppressed exceptions. In Python the pattern is try/except/else/finally.
Follow-up
- What happens if an exception is thrown inside a catch block, or inside finally?
- When would you write a custom exception, and should it be checked or unchecked?
- Why is catching Exception or Throwable at every layer a problem?
Write a function to reverse a string without using built-in library functions.
Medium · Data Structures & Coding Challenges
Approach
- Clarify the language first. Java and Python strings are immutable, so copy into a char array or list, reverse it in place, then build a new string. That is O(n) time and O(n) extra space; on a mutable C buffer it is O(1) extra space.
- Two pointers: i = 0 and j = n - 1, swap chars[i] and chars[j], then move both inward while i < j. This does n/2 swaps and handles odd lengths with no special case.
- Avoid result = result + c in a Java loop: each concatenation copies the whole string, so the loop is O(n^2). A recursive version uses O(n) stack and can overflow on long input.
- Edge cases to state and test: null, empty string, one character, an even and an odd length. Reversing UTF-16 code units splits surrogate pairs such as emoji, so mention code-point-aware reversal if the input can contain them.
Follow-up
- Reverse the order of the words in a sentence in place (reverse the whole string, then each word).
- How would you reverse a string with recursion, and what does that cost?
- How does your solution change if the input contains emoji or combining characters?
How do you find the second largest number in an unsorted array?
Medium · Data Structures & Coding Challenges
Approach
- Clarify whether duplicates count: for [5, 5, 3], is the answer 5 or 3? The usual reading is the second largest distinct value, so 3.
- Use one pass with two variables. If x > first, set second = first and first = x; else if x < first and x > second, set second = x. That is O(n) time and O(1) space, against O(n log n) for sorting.
- Initialise carefully. Starting at Integer.MIN_VALUE gives a wrong answer when MIN_VALUE is in the data, so use a boolean flag, a nullable wrapper or a wider type to mean 'not set yet'.
- Edge cases: fewer than two elements, or every element equal, means there is no answer. Return an Optional, a sentinel the caller checks, or throw, and say which one you chose. Test with negatives and with the maximum at index 0.
Follow-up
- Generalise to the kth largest: compare a min-heap of size k (O(n log k)) with quickselect (average O(n)).
- How would you do this over a stream you can read only once?
- What is the minimum number of comparisons needed to find both the largest and the second largest?
Write a program to check whether a given string or number is a palindrome.
Medium · Data Structures & Coding Challenges
Approach
- Strings: two pointers from both ends compare characters and move inward until they meet. O(n) time, O(1) extra space, and no need to build a reversed copy.
- Ask about the rules first: is the check case-sensitive, and should spaces and punctuation be ignored, as in 'A man, a plan, a canal: Panama'? If so, skip non-alphanumeric characters with the pointers and compare lowercased characters.
- Numbers without converting to a string: negatives are not palindromes, and neither is any non-zero number ending in 0. Reverse only half: while x > rev, set rev = rev * 10 + x % 10 and x = x / 10. Then x == rev, or x == rev / 10 for odd digit counts. This avoids overflowing the reversed value.
- Test: empty string, one character, even and odd lengths, 0, 10, 121, -121.
Follow-up
- Find the longest palindromic substring (expand around each centre, O(n^2)).
- Check whether a singly linked list is a palindrome in O(1) extra space.
- Can the characters of a string be rearranged into a palindrome? (At most one character may have an odd count.)
Write a function to remove duplicate elements from an array or list.
Medium · Data Structures & Coding Challenges
Approach
- Ask whether order must be kept and whether the input is sorted, because that decides the algorithm.
- Unsorted, order kept: walk the input with a hash set of seen values and append only unseen ones. O(n) time, O(n) space. In Java, LinkedHashSet gives the same result; in Python, list(dict.fromkeys(xs)) works because dicts keep insertion order from 3.7. set(xs) on its own loses the order.
- Sorted array: two pointers in place. A write index advances only when the current value differs from the last one written. O(n) time, O(1) extra space, and it returns the new length.
- No extra memory and unsorted: sort first (O(n log n), loses the original order) or use nested loops (O(n^2)). For custom objects, deduplication depends on equals() and hashCode() being consistent, so mention that.
Follow-up
- Keep at most two copies of each value in a sorted array, in place.
- How would you remove duplicates from an unsorted linked list without a buffer?
- Two Employee objects count as duplicates when their ids match. What do you implement so a HashSet sees that?
Swap two numbers without using a third variable, and demonstrate how to perform the swap using bitwise XOR ope
Medium · Data Structures & Coding Challenges
Swap two numbers without using a third variable, and demonstrate how to perform the swap using bitwise XOR operations.
Approach
- Arithmetic version: a = a + b; b = a - b; a = a - b. In C and C++, signed overflow in a + b is undefined behaviour. In Java, int arithmetic wraps and the swap still comes out right, but floating-point values can lose precision. The multiply/divide version fails when either value is 0.
- XOR version: a ^= b; b ^= a; a ^= b. It works because x ^ x = 0 and x ^ 0 = x, so it cannot overflow. Trace it on a = 5 (101) and b = 3 (011): a becomes 110, b becomes 101 (5), a becomes 011 (3).
- Aliasing trap: if both operands refer to the same memory location, for example swap(&x, &x) in C, the first step zeroes the value. Guard against the same address, not just equal values.
- XOR swap works only on integer types. Modern compilers make a temporary-variable swap at least as fast, so this is a fundamentals exercise. In Python, a, b = b, a is the normal way.
Follow-up
- Why does the XOR swap zero the value when both operands are the same variable?
- Use XOR to find the one element that appears once in an array where every other element appears twice.
- Would you use either trick in production code? Why or why not?
Write an SQL query to find the second highest salary from an Employee table.
Medium · Database Management & SQL Queries
Approach
- Portable version: SELECT MAX(salary) FROM Employee WHERE salary < (SELECT MAX(salary) FROM Employee). Ties at the top are handled, and when no second salary exists it returns NULL rather than an empty result.
- Window version: rank the distinct salaries with DENSE_RANK() OVER (ORDER BY salary DESC) in a subquery and keep rank = 2. Explain why DENSE_RANK is right here, while RANK leaves gaps after ties and ROW_NUMBER breaks ties arbitrarily.
- LIMIT version for MySQL and PostgreSQL: SELECT DISTINCT salary ... ORDER BY salary DESC LIMIT 1 OFFSET 1. Without DISTINCT, duplicate top salaries give the wrong answer. Oracle 12c+ uses OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY. Wrap it as a scalar subquery if the caller needs NULL instead of zero rows.
- NULL salaries: MAX ignores them, but PostgreSQL sorts NULLs first under DESC, so add WHERE salary IS NOT NULL to the ORDER BY versions.
Follow-up
- Return the Nth highest salary for any N, or the second highest per department with PARTITION BY.
- Find every employee whose salary is above their own department's average.
- Which version still performs well on a large table, and which index helps?
What is the operational difference between DELETE, TRUNCATE, and DROP commands in SQL?
Medium · Database Management & SQL Queries
Approach
- DELETE is DML. It removes the rows a WHERE clause matches (or every row), one row at a time with per-row logging, fires DELETE triggers, checks foreign keys row by row, and can be rolled back inside a transaction. Identity or auto-increment counters are not reset.
- TRUNCATE removes all rows by deallocating data pages. It takes no WHERE, does not fire row-level DELETE triggers, and is much faster on large tables. It fails when another table's foreign key references the table (PostgreSQL needs CASCADE).
- Rollback depends on the database: in Oracle and MySQL, TRUNCATE is DDL with an implicit commit, so it cannot be rolled back. In PostgreSQL and SQL Server it is transactional. MySQL and SQL Server reset the auto-increment counter; PostgreSQL resets sequences only with RESTART IDENTITY.
- DROP removes the table itself: definition, data, indexes, triggers and grants. Views or foreign keys that depend on it break or need CASCADE. Close with a rule of thumb: DELETE for selective removal, TRUNCATE to empty a table, DROP when the table should no longer exist.
Follow-up
- You ran DELETE without a WHERE in production. What can you still recover, and how?
- Why is deleting millions of rows with one DELETE slow, and how would you batch it?
- What do ON DELETE CASCADE and ON DELETE SET NULL do when a parent row is deleted?
Explain the concept of primary keys and foreign keys, and write an INNER JOIN query connecting two tables.
Medium · Database Management & SQL Queries
Approach
- A primary key uniquely identifies each row. It cannot be NULL, a table has only one (it may be composite), and the database enforces it with a unique index. A foreign key is a column that must match a primary or unique key in another table, so an employee's dept_id must point at an existing department.
- Write the join: SELECT e.emp_name, d.dept_name FROM Employees e INNER JOIN Departments d ON e.dept_id = d.dept_id;
- State what INNER JOIN drops: employees whose dept_id is NULL and departments with no employees. Switch to LEFT JOIN when those rows must appear.
- Practical points: foreign keys block orphan inserts and control parent deletes (RESTRICT, CASCADE, SET NULL). MySQL InnoDB creates an index on a foreign key column if none exists; PostgreSQL does not, so index the column yourself to keep joins and parent deletes fast.
Follow-up
- List the departments that have no employees.
- Surrogate key or natural key: which would you choose for Employees, and why?
- Can a foreign key column be NULL, and what does that mean for the joins?
Write an SQL query to extract the first three characters from a text column across all rows.
Medium · Database Management & SQL Queries
Approach
- Standard SQL: SELECT SUBSTRING(col FROM 1 FOR 3) FROM t. Positions start at 1, not 0.
- Dialects: MySQL and SQL Server accept SUBSTRING(col, 1, 3) and LEFT(col, 3); PostgreSQL has LEFT, SUBSTRING and SUBSTR; Oracle uses SUBSTR(col, 1, 3) and has no LEFT. Name the dialect you are writing in.
- Edge cases: values shorter than three characters come back whole, and NULL stays NULL, so wrap the column in COALESCE if the output needs a value. With UTF-8 text, MySQL, PostgreSQL and Oracle SUBSTR count characters, not bytes.
- If the prefix is used to filter, WHERE LEFT(col, 3) = 'abc' wraps the column in a function, so a plain index on col cannot be used. WHERE col LIKE 'abc%' can use the index.
Follow-up
- Return the last three characters instead.
- Count rows per three-character prefix and show only prefixes that appear more than once.
- Why can LIKE 'abc%' use an index while LIKE '%abc' cannot?
How do GROUP BY and HAVING clauses differ, and how would you write a query to count employees per departme
Medium · Database Management & SQL Queries
How do GROUP BY and HAVING clauses differ, and how would you write a query to count employees per department?
Approach
- Use the logical order of evaluation: FROM/JOIN, then WHERE, GROUP BY, HAVING, SELECT, ORDER BY. WHERE filters single rows before grouping and cannot use aggregates. GROUP BY collapses rows into groups. HAVING filters those groups and can use COUNT, SUM and AVG.
- Query: SELECT d.dept_name, COUNT(e.emp_id) AS headcount FROM Departments d LEFT JOIN Employees e ON e.dept_id = d.dept_id GROUP BY d.dept_id, d.dept_name;
- Point out COUNT() vs COUNT(e.emp_id). After a LEFT JOIN, an empty department still produces one row, so COUNT() reports 1 where COUNT(e.emp_id) correctly reports 0.
- Every selected column that is not aggregated must appear in GROUP BY (MySQL enforces this under ONLY_FULL_GROUP_BY). For 'departments with more than 5 members', add HAVING COUNT(e.emp_id) > 5, repeating the aggregate rather than its alias for portability.
Follow-up
- Show only the departments whose average salary is above the company-wide average.
- Can you use HAVING without GROUP BY, and what does it do then?
- Why would a condition such as status = 'active' go in WHERE rather than in HAVING?
Why do you want to join Cognizant, and are you comfortable relocating or shifting to a new tech stack based on
Medium · Behavioral & Project Scenarios
Why do you want to join Cognizant, and are you comfortable relocating or shifting to a new tech stack based on project needs?
Approach
- Answer the two parts separately. Candidates report that this question pairs motivation with relocation and changing tech stacks, so a vague answer to the second half stands out.
- For motivation, use facts about the role that you can back up. The work candidates describe is client projects across healthcare, financial services, retail and manufacturing, on Java, Python or .NET back ends, React or Angular front ends, and AWS or Azure. Link one or two of these to your own projects or to the track you applied through.
- On stack changes, give evidence rather than just saying yes. Name a time you picked up a new language or framework for a project, how long it took, and what you shipped with it.
- On relocation, be honest and specific. If you have a real constraint, state it now instead of agreeing and backing out later, since candidates report that location comes up again in the HR stage.
Follow-up
- If you were placed on a maintenance or support project instead of new development, how would you approach it?
- Which stack would you choose if you had the choice, and how would you handle being assigned a different one?
- Are you open to working shifts that overlap with clients in other time zones?
Explain the four main pillars of Object-Oriented Programming (OOP) and provide real-world examples for each.
Medium · Core Programming & OOP Concepts
Approach
- Give each pillar a one-line definition and one banking example: encapsulation is a BankAccount whose balance field is private and changes only through deposit() and withdraw(), which reject negative amounts and overdrafts.
- Abstraction: a PaymentMethod interface with pay(amount); checkout code calls pay() without knowing whether a card, UPI or wallet class sits behind it. Say how it differs from encapsulation: abstraction hides which implementation runs, encapsulation protects an object's state.
- Inheritance: SavingsAccount and CurrentAccount extend Account and reuse its fields and methods. Add that inheritance only fits a true is-a relationship, and composition is the safer default otherwise.
- Polymorphism: compile-time through overloading (several deposit() signatures) and runtime through overriding, where an Account reference calls SavingsAccount.calculateInterest() via dynamic dispatch. Write the short class skeleton to show it.
Follow-up
- When would you pick an abstract class over an interface, now that Java interfaces can have default methods?
- Why does Java forbid multiple inheritance of classes, and how do interfaces avoid the diamond problem?
- Show a case where inheritance was the wrong choice and composition fixes it.
What is the difference between method overloading and method overriding in Java or C++?
Medium · Core Programming & OOP Concepts
Approach
- Overloading means the same method name with a different parameter list (number, type or order of parameters). The compiler picks the version from the static argument types, which is why it is called compile-time polymorphism. A different return type on its own is not a valid overload.
- Overriding means a subclass gives its own body for a method with the same signature. The return type must match or be covariant, access cannot be narrowed, and in Java an override cannot throw broader checked exceptions. The call is resolved at runtime from the object's actual class.
- Java edge cases: static methods are hidden, not overridden; private and final methods cannot be overridden; @Override makes the compiler catch a signature typo.
- C++ difference: a call through a base pointer or reference dispatches dynamically only when the base method is virtual. Mark derived methods override. A derived function with the same name hides every base overload unless you add using Base::f.
Follow-up
- Can you overload or override main() or a static method in Java?
- How does Java choose between overloads when widening, autoboxing and varargs could all apply?
- What happens in C++ if you forget the virtual keyword on the base method?
Explain how final, finally, and finalize differ in Java.
Medium · Core Programming & OOP Concepts
Approach
- They only share a spelling. final is a modifier: a final variable can be assigned once, a final method cannot be overridden, a final class cannot be subclassed (String is one). A final reference does not make the object it points to immutable.
- finally is a block after try/catch that runs whether the try completes normally, returns, or throws. It is skipped only if the JVM stops: System.exit(), a crash or a killed process.
- finalize() is a method on Object that the garbage collector may call before it reclaims an object. Nothing guarantees when it runs, or that it runs at all. It was deprecated in Java 9 and marked for removal in Java 18.
- Say what replaces finalize(): try-with-resources on an AutoCloseable for deterministic cleanup, and java.lang.ref.Cleaner as a last-resort safety net.
Follow-up
- If both the try block and the finally block contain a return statement, which value does the caller get?
- What does 'effectively final' mean, and why do lambdas and anonymous classes require it?
- How would you make a class fully immutable, beyond declaring its fields final?
What are the key differences between a list, tuple, and set in Python?
Medium · Core Programming & OOP Concepts
Approach
- List: mutable, ordered, allows duplicates. Index access is O(1), append is amortised O(1), insert at the front and the
incheck are O(n). - Tuple: immutable and ordered. A tuple is hashable when every element is, so it can be a dict key or a set member, for example a (lat, lon) key. A tuple that holds a list is not hashable, and that inner list can still be changed.
- Set: mutable, unordered, no duplicates, and elements must be hashable. Average O(1) for add, remove and membership, plus union, intersection and difference. frozenset is the immutable, hashable version.
- Close with when to use each: a list for an ordered sequence you change, a tuple for a fixed record or key, a set for membership tests and deduplication. Mention that {} creates an empty dict, so an empty set is written set().
Follow-up
- Why can a list not be a dictionary key?
- How would you remove duplicates from a list while keeping the original order?
- Is a tuple really immutable if it contains a list? Show what happens.
What is the structural difference between Spring and Spring Boot, and how does dependency injection work?
Medium · Web Development & Cloud Frameworks
Approach
- Spring Framework is the base: an IoC container, dependency injection, AOP, transaction management and Spring MVC. You configure it yourself (XML or @Configuration classes), choose and line up the library versions, and traditionally deploy a WAR to an external server.
- Spring Boot is built on Spring. It adds auto-configuration based on the classpath (@SpringBootApplication combines @Configuration, @EnableAutoConfiguration and @ComponentScan), starter dependencies with matched versions, an embedded server (Tomcat by default) in a runnable jar, external configuration through application.properties or YAML, and Actuator endpoints.
- Dependency injection: the container creates beans (found through @Component, @Service, @Repository or @Bean methods) and supplies their dependencies, so classes do not construct their own collaborators. Singleton is the default scope.
- Prefer constructor injection: dependencies can be final, a missing one fails at startup, and the class can be unit-tested with plain new. Since Spring 4.3 a single constructor needs no @Autowired. Field injection hides dependencies and needs reflection in tests. When two beans match a type, resolve it with @Qualifier or @Primary.
Follow-up
- How do you replace a bean that Spring Boot auto-configures (for example, what @ConditionalOnMissingBean does)?
- What happens with a circular dependency under constructor injection, and how would you remove it?
- What is the difference between @Component, @Service, @Repository and @Bean?
Explain the concept of the Virtual DOM and custom hooks in React.
Medium · Web Development & Cloud Frameworks
Approach
- Virtual DOM: a component returns a tree of plain JavaScript element objects. When state or props change, React renders a new tree, compares it with the previous one (reconciliation), and then applies only the changed DOM operations in the commit phase.
- Explain the diff heuristics. An element of a different type replaces its whole subtree; the same type updates only changed attributes; children in a list are matched by key. Using the array index as a key breaks when items are inserted or reordered, because state ends up attached to the wrong row. These heuristics make the diff roughly O(n) instead of a general tree diff.
- Do not claim the virtual DOM always beats direct DOM updates. Its value is the declarative model: you describe the UI for a given state and React works out the changes.
- Custom hook: a function whose name starts with use and calls other hooks to share stateful logic, for example useFetch(url) returning { data, error, loading }. It uses useState plus useEffect with [url] as the dependency array, and its cleanup aborts the request with AbortController. Each component that calls it gets its own state.
- Rules of hooks: call them only at the top level of components or other hooks, never inside conditions or loops, because React matches state to hooks by call order.
Follow-up
- Why does a list need a stable key, and what bug do index keys cause?
- When would you reach for React.memo, useMemo or useCallback, and what do they cost?
- Why does the order of hook calls matter, and what breaks if a hook is called conditionally?
What is the Circuit Breaker design pattern in microservices, and why is it important for resilience?
Medium · Web Development & Cloud Frameworks
Approach
- A circuit breaker wraps calls to a remote dependency and has three states. Closed: calls go through and failures are counted over a sliding window. Open: once the failure rate passes a threshold, calls fail immediately or return a fallback without reaching the dependency. Half-open: after a wait, a few trial calls go through; success closes the breaker, failure opens it again.
- Why it matters: without one, callers wait on timeouts to a dead service and exhaust their own threads and connection pools, so one failure spreads through the call chain. Failing fast protects the caller and gives the dependency room to recover.
- Pair it with other patterns: timeouts on every call, retries with exponential backoff and jitter, bulkheads that cap concurrent calls per dependency, and a fallback such as cached data or a degraded response. In Java the usual library is Resilience4j, used through Spring Cloud CircuitBreaker. Hystrix has been in maintenance mode since 2018.
- Tuning and edge cases: failure-rate threshold, minimum number of calls before the breaker can trip, slow-call threshold, wait time in open state. Count timeouts and 5xx responses, not 4xx client errors. Emit metrics and alerts on state changes.
Follow-up
- How do retries and the circuit breaker interact, and which one should wrap the other?
- Each service instance has its own breaker. Is that a problem, or should the state be shared?
- What fallback makes sense for a payment call, where faking success is not an option?
Describe the core differences between containerization using Docker and orchestration using Kubernetes.
Medium · Web Development & Cloud Frameworks
Approach
- Docker packages an application and its dependencies into an image (built in layers from a Dockerfile) and runs it as a container. A container is an isolated process on the host kernel, using namespaces for isolation and cgroups for resource limits; it is not a virtual machine with its own kernel.
- Kubernetes orchestrates containers across a cluster of machines. It schedules Pods onto nodes; Deployments and ReplicaSets keep the desired number of replicas and restart failed ones; Services give a stable address and load balancing; it also handles rolling updates and rollbacks, ConfigMaps and Secrets, and Horizontal Pod Autoscaling.
- How they relate: Docker builds the image and runs it on one host, and Kubernetes decides where, how many and what happens on failure. Kubernetes runs OCI images through a runtime such as containerd. Its built-in Docker support (dockershim) was removed in 1.24, but images built with Docker still run.
- Trade-off: Kubernetes adds real operational cost. Docker Compose on one host can be enough for a small system, and managed services such as EKS or AKS take over the control plane.
Follow-up
- What is the difference between a liveness probe and a readiness probe?
- How does a rolling update avoid downtime, and how do you roll it back?
- How does a container differ from a virtual machine in isolation and startup cost?
Explain the difference between GET and POST HTTP methods when building RESTful APIs.
Medium · Web Development & Cloud Frameworks
Approach
- GET reads a resource. Parameters go in the path or query string. It is safe (no intended side effects) and idempotent, so it can be cached, bookmarked and retried freely. A body on a GET has no defined meaning, so do not rely on one.
- POST sends a payload in the body for the server to process, usually to create a resource or trigger an action. It is neither safe nor idempotent: sending it twice can create two orders. A typical create returns 201 Created with a Location header.
- Security: query strings end up in server logs, browser history and Referer headers, so secrets never go in a GET URL. A POST body is not encrypted either, so both need HTTPS.
- Practical limits and retries: servers cap URL length, which pushes large or complex inputs into a POST body. A retry-safe POST needs an idempotency key the server stores. Contrast PUT (idempotent full replace) and PATCH (partial update).
Follow-up
- When would you use PUT instead of POST, and why is PUT idempotent?
- A client times out and retries a POST that creates a payment. How do you prevent a duplicate?
- Which status codes would you return for a validation error, a missing resource and a conflicting update?
p99 jumped on one listing filter while p50 stayed flat
Medium · query planning · composite index · percentiles
After a release that added an owner_user_id filter to the resource listing, p99 rose from 90 ms to 1.9 s while p50 stayed at 40 ms. Traffic and row counts are unchanged. resource carries the index (tenant_id, status, updated_at DESC, resource_id DESC). The new query filters tenant_id and owner_user_id, orders by updated_at DESC, resource_id DESC, and takes 20 rows. On PostgreSQL, explain the shape of the regression, prove it from a query plan, and give the index you would add.
Approach
- Start from the shape. A flat p50 with a moved p99 means a subset of requests changed cost, not all of them, so the first job is naming the subset. Bucket the endpoint's latency by the tenant's row count; the natural hypothesis is that large tenants are a small share of requests and all of the tail.
- Get the plan for the new query on a large tenant with EXPLAIN (ANALYZE, BUFFERS). Expect an index scan over the tenant's range, a filter discarding most of it, then a Sort feeding the Limit, possibly reporting Sort Method: external merge Disk. Read actual rows on the scan node, not estimated.
- Explain why the existing index cannot serve it. A composite B-tree is seekable only as a left prefix, and with no equality predicate on status the scan cannot treat updated_at as an ordering, because rows in the tenant's range are ordered by status first. Everything matching must be read and sorted before LIMIT 20 can apply, so a tenant with 400,000 rows pays 400,000 rows to return 20.
- Add (tenant_id, owner_user_id, updated_at DESC, resource_id DESC). Equality on the first two columns leaves the index ordered by updated_at within that pair, so the plan becomes an index scan that stops after 20 rows with no Sort node. PostgreSQL can scan a B-tree backwards, so the DESC markers matter only if the two sort columns ever disagree in direction; keeping them explicit documents the order the keyset cursor depends on.
Follow-up
- The endpoint paginates with OFFSET. What does page 500 cost with your index, and what does the keyset version cost?
- How would you have caught this before release, given that a 10,000-row seed database produces the same plan shape at an unnoticeable cost?
Suggested practice checklist
The plan follows the three reported rounds: Day 1 sets up the screening material, Days 2 to 5 cover OOP, coding, SQL and framework questions candidates report, and Days 6 and 7 rehearse the project and behavioral stories and run a full mock.
Day 1 — Screening material and resume inventory
- Write your two-minute introduction covering education, core language, key projects and why Cognizant, and record yourself saying it once.
- Answer the question about why you want to join and whether you would relocate or shift stack, in four or five sentences.
- List every technology on your resume and cross out any you could not explain for two minutes.
Deliverable: A written introduction, a written answer on joining, relocating and changing stack, and a pruned resume technology list.
Day 2 — OOP and Java fundamentals
- Write a class sketch for each of the four OOP pillars and explain the pillars aloud with a real-world example.
- Write one overloading and one overriding example and say which is resolved at compile time.
- Explain final, finally and finalize, and what happens when an exception is thrown inside try with no matching catch, with code that shows finally running after a return.
Deliverable: Four class sketches, two short code examples for overload and override, and one finally-after-return snippet, each explained aloud.
Day 3 — Python collections and core coding problems
- Write the list, tuple and set comparison from memory: mutability, ordering, duplicates, hashing and lookup cost.
- Solve reverse a string, second largest, palindrome and remove duplicates in your primary language without built-in helpers, in a plain editor.
- Do the XOR swap and write out why it fails when both names point to the same value, then state time and space complexity for all five.
Deliverable: Five working programs with complexity noted, plus a one-page list, tuple and set comparison.
Day 4 — SQL queries and DDL semantics
- Create an Employee and a Department table in MySQL or PostgreSQL and load a few rows with a tie in salary and one department with no employees.
- Write the second-highest-salary query two ways, the first-three-characters query, an INNER JOIN on a primary and foreign key, and employees per department with GROUP BY and HAVING.
- Write a comparison of DELETE, TRUNCATE and DROP covering row removal, WHERE, triggers and rollback.
Deliverable: A saved SQL file with five working queries, run against your test data, and a three-way comparison table.
Day 5 — Framework and architecture answers
- Explain the structural difference between Spring and Spring Boot and how dependency injection works, then write a short constructor-injection example.
- Explain the Virtual DOM and write one custom hook, then explain the Circuit Breaker pattern and its closed, open and half-open states.
- Write the difference between Docker and Kubernetes and between GET and POST for REST APIs, using one concrete endpoint as the example.
Deliverable: Five spoken answers with a code or diagram aid for each, recorded or written out.
Day 6 — Project walkthrough and behavioral stories
- Fill in the one-page project sheet for your main project: your role, request flow, tables, libraries, two decisions and one bug.
- Write STAR stories for a changed deadline, a technical disagreement and learning a new stack quickly, each with a measurable or visible result.
- Deliver the project walkthrough aloud to another person or a recording, using only the sheet.
Deliverable: A one-page project sheet, three written STAR stories and one recorded walkthrough.
Day 7 — Full mock loop
- Run a mock of the whole loop in order: introduction, two coding problems and one SQL query written live while narrating, then one framework question and one project question.
- Write down the three answers that were weakest and fix each with one more repetition.
Deliverable: One recorded mock run, a debugging write-up, and a list of three fixed answers.
Project and adaptability stories
Candidates report that the final stage includes managerial and HR conversations alongside the technical ones, covering your project, how you handle pressure and disagreement, how quickly you pick up new stacks, and whether you can relocate. Prepare stories with a real project, your own actions and a visible result, and keep them in the first person.
- Why do you want to join Cognizant, and are you comfortable relocating or shifting to a new tech stack based on project needs?
Walk me through your primary technical project, highlighting your personal role, design decisions, and major c
Medium · Behavioral & Project Scenarios
Walk me through your primary technical project, highlighting your personal role, design decisions, and major challenges faced.
Approach
- Choose one project where you can name your own part: the modules, tables or endpoints you built, not the team's. Give two sentences of context (users, purpose, stack) and then spend your time on your decisions.
- Walk the architecture in request order: client, controller or API layer, service logic, database, any external call. Be ready to sketch the main tables with their primary and foreign keys, since schema questions follow naturally from any project with a database.
- Pick two design decisions and say what you rejected and why, for example a join table instead of a repeated column, or a synchronous call instead of a queue. Use "I chose X because Y" so your reasoning is audible, not just the outcome.
- Tell one challenge as a debugging sequence: the symptom, how you reproduced it, what you checked in order, the fix, and how you confirmed it. Include one wrong guess; it makes the story credible.
- Only describe technologies you can explain. Before the interview, take each library and framework on your resume and write one sentence on what it did in this project and why it was chosen.
Follow-up
- Why did you design the tables that way, and what would break if the data grew a hundred times?
- What would you change if you rebuilt this project today?
- Which part did a teammate own, and how did your piece connect to theirs?
How do you manage unexpected project deadlines or shifting priorities under pressure?
Medium · Behavioral & Project Scenarios
Approach
- Choose one concrete episode, such as a release date moved forward or a requirement replaced mid-sprint. State the original plan and exactly what changed, in two sentences.
- Show triage: list the remaining tasks, estimate each, separate what must ship from what can wait, note dependencies, then say what you cut, reordered or split.
- Show communication: tell your lead or the client's technical contact early and offer options (reduced scope, a later date, extra help) rather than absorbing the change silently. Name who agreed to the trade-off.
- Say what you protected, for example tests on the changed path and code review, so speed did not turn into defects. Close with the plain result: what shipped, what moved to the next sprint, what you changed afterwards.
- The story that sinks this answer is only long hours with no prioritisation, or one where nobody else knew a deadline was at risk.
Follow-up
- What did you deliberately leave out, and who accepted that?
- What would you do if two stakeholders asked for conflicting priorities in the same week?
- What did you change afterwards so the next shift hurt less?
Describe a situation where you had a disagreement with a team member on a technical approach and how you resol
Medium · Behavioral & Project Scenarios
Describe a situation where you had a disagreement with a team member on a technical approach and how you resolved it.
Approach
- Choose a disagreement about a technical decision (data structure, framework choice, API shape, how to write a query), not a personality clash. State both positions fairly in one sentence each.
- Show that you understood the other view first: restate it in your own words and ask what constraint drives it, such as deadline, team skills or existing code.
- Settle it with evidence rather than seniority: a small prototype, a measurement, the documentation, the written requirement, or an agreed escalation to the technical lead. Name the criteria you used to decide.
- Report the outcome honestly, including if the other approach won or you combined the two, and say how you worked together afterwards.
- Avoid a story where you were simply right and the colleague was careless; it shows no listening. Also avoid one with no technical content to examine.
Follow-up
- What would you have done if your lead had overruled you after seeing the evidence?
- How would you decide if no data could settle it?
- Was there a time you turned out to be wrong, and what did you do?
How do you approach learning a completely new framework or technology stack within a tight timeline?
Medium · Behavioral & Project Scenarios
Approach
- Use a real case where a deadline forced a new stack, such as moving from Java and Spring Boot to Django or adding React to a back-end project. Name the date and what had to work by then.
- Describe your method: scope what the task actually needs, follow the official quickstart, build a thin end-to-end slice first, map new concepts to ones you know (dependency injection, ORM, routing, component state), then widen.
- Show how you verified your work: tests, comparison with an existing module in the code base, and a code review request. Say that you tried to solve a question yourself first and then asked a colleague a specific one.
- State the result and the gaps that remained, and how you scheduled time to close them. Candidates report that stack changes follow client projects, so present learning on the job as routine for you.
- The weak version lists courses watched with no deliverable. The strong version ends with something that shipped and was reviewed.
Follow-up
- What did you skip at first that later caused problems?
- How do you decide when to stop researching and ask someone?
- How would you ramp up on a client code base that is large and poorly documented?