Sunday, September 14, 2025

Cognizant interview questions

The questions are typically based on:

  • Programming fundamentals
  • Database knowledge
  • Basic software engineering concepts
  • Problem-solving (Data Structures & Algorithms)
  • Aptitude and reasoning (in assessment tests)

Here’s a list of relevant technical assessment questions categorized by topic:

Programming Fundamentals (C/C++/Java/Python)

  1. What is the difference between a compiled and an interpreted language?
  2. What are the basic data types in C?
  3. Explain the concept of Object-Oriented Programming (OOP).
  4. What is the difference between == and .equals() in Java?
  5. How is memory managed in Python?

Data Structures & Algorithms

  1. What is the difference between an array and a linked list?
  2. Implement a program to reverse a string.
  3. Write a program to check if a number is a palindrome.
  4. What is the time complexity of searching in a binary search tree?
  5. Explain stack vs queue. Where would you use each?

Database Management Systems (DBMS)

  1. What is the difference between SQL and NoSQL?
  2. Write an SQL query to fetch the second-highest salary from a table.
  3. What are the different types of joins in SQL?
  4. Explain normalization and its types.
  5. What is the use of the GROUP BY clause in SQL?

Operating Systems & Networking

  1. What is the difference between a process and a thread?
  2. What is deadlock and how can it be prevented?
  3. What is virtual memory?
  4. Explain the OSI model in networking.
  5. What is the difference between TCP and UDP?

OOPs Concepts (For Java/C++ roles)

  1. What are the four pillars of OOP?
  2. What is polymorphism? Provide an example.
  3. Difference between abstraction and encapsulation.
  4. What is inheritance? Types of inheritance in C++.
  5. What is a constructor and destructor?

Coding/Problem-Solving (Beginner Level)

  1. Write a program to find the factorial of a number.
  2. Write a program to print the Fibonacci series.
  3. Check if a given string is a palindrome.
  4. Write a program to find the largest element in an array.
  5. Count the number of vowels in a string.

Aptitude and Logical Reasoning (For Written Assessments)

  1. If the cost price of 15 articles is equal to the selling price of 10 articles, find the profit percentage.
  2. Solve puzzles involving number patterns or sequences.
  3. Logical reasoning: blood relations, directions, seating arrangement.
  4. Time and work problems.
  5. Percentage, ratio & proportion-based problems.

Behavioral/HR Readiness (for Final Rounds)

(Not technical, but part of the full fresher pipeline.)

  • Tell me about yourself.
  • Why Cognizant?
  • Explain a project you've worked on.
  • Are you open to relocation?
  • How do you handle pressure or deadlines?

Tips for Freshers:

  • Practice basic coding problems from platforms like HackerRank, GeeksforGeeks, or LeetCode (easy level).
  • Understand fundamentals clearly rather than just memorizing definitions.
  • Be honest in what you know; don’t try to fake knowledge in interviews.

 

 

===========================================

===========================================

These questions are often simple to moderate in difficulty and are designed to test your logic, problem-solving, and programming fundamentals.

 

1. Factorial of a Number

Question:
Write a program to find the factorial of a given number using iteration and recursion.

Explanation:

  • Factorial of n (n!) = n × (n-1) × (n-2) × ... × 1
  • Example: 5! = 5×4×3×2×1 = 120

Variants:

  • Use recursion.
  • Handle edge cases like 0! = 1.

Sample Code (Python):

def factorial(n):

    if n == 0 or n == 1:

        return 1

    return n * factorial(n - 1)

 

2. Fibonacci Series

Question:
Print the first n numbers in the Fibonacci sequence.

Explanation:
Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, ...

  • Each number is the sum of the two preceding ones.

Variants:

  • Generate first n terms.
  • Find the nth Fibonacci number.
  • Use recursion and iteration both.

Sample Code (Python):

def fibonacci(n):

    a, b = 0, 1

    for _ in range(n):

        print(a, end=" ")

        a, b = b, a + b

 

3. Palindrome Checker

Question:
Check whether a string or number is a palindrome.

Explanation:
A palindrome reads the same backward as forward.

  • Examples: madam, 121

Variants:

  • Case-insensitive comparison.
  • Ignore non-alphanumeric characters.

Sample Code (Python):

def is_palindrome(s):

    return s == s[::-1]

 

4. Largest Element in an Array

Question:
Find the largest number in a given list/array.

Explanation:
Iterate through the array and track the maximum.

Variants:

  • Find 2nd largest.
  • Find k-th largest using sorting or heaps.

Sample Code (Python):

def find_largest(arr):

    max_val = arr[0]

    for num in arr:

        if num > max_val:

            max_val = num

    return max_val

 

5. Count Vowels in a String

Question:
Count the number of vowels in a given string.

Explanation:
Check each character against a, e, i, o, u.

Variants:

  • Handle both uppercase and lowercase.
  • Return a dictionary of each vowel count.

Sample Code (Python):

def count_vowels(s):

    vowels = "aeiouAEIOU"

    count = 0

    for char in s:

        if char in vowels:

            count += 1

    return count

 

6. Check Prime Number

Question:
Check if a number is prime.

Explanation:
A number is prime if it has only 2 factors: 1 and itself.

Variants:

  • List all primes up to N (Sieve of Eratosthenes).
  • Count prime numbers in a range.

Sample Code (Python):

def is_prime(n):

    if n <= 1:

        return False

    for i in range(2, int(n**0.5)+1):

        if n % i == 0:

            return False

    return True

 

7. Sum of Digits

Question:
Find the sum of digits of a number.

Explanation:
Example: 123 → 1 + 2 + 3 = 6

Sample Code (Python):

def sum_of_digits(n):

    return sum(int(digit) for digit in str(n))

 

8. Armstrong Number

Question:
Check if a number is an Armstrong number.

  • A number is Armstrong if the sum of its digits raised to the power of the number of digits equals the number itself.

Example:

  • 153 → 1³ + 5³ + 3³ = 153

Sample Code (Python):

def is_armstrong(n):

    digits = str(n)

    power = len(digits)

    total = sum(int(d)**power for d in digits)

    return total == n

 

9. Swap Two Numbers Without a Temp Variable

Explanation:
Test knowledge of arithmetic or bitwise operations.

Variants:

  • Use arithmetic: a = a + b, etc.
  • Use XOR swap.

Sample Code (Python):

a, b = 5, 10

a, b = b, a

 

10. Remove Duplicates from a List

Question:
Write a program to remove duplicates from a list.

Variants:

  • Preserve order.
  • Return unique list or count.

Sample Code (Python):

def remove_duplicates(lst):

    return list(set(lst))

 

11. Sorting Without Built-in Function

Question:
Implement bubble sort or selection sort.

Explanation:
Good to test understanding of sorting algorithms.

Sample Code (Python): Bubble Sort

def bubble_sort(arr):

    n = len(arr)

    for i in range(n):

        for j in range(0, n-i-1):

            if arr[j] > arr[j+1]:

                arr[j], arr[j+1] = arr[j+1], arr[j]

 

12. Find Missing Number in an Array

Question:
Given n numbers in the range 1 to n+1 with one missing, find it.

Approach:

  • Sum formula: expected_sum = n*(n+1)//2

Sample Code (Python):

def find_missing(arr):

    n = len(arr) + 1

    total = n * (n + 1) // 2

    return total - sum(arr)

***********************************************************

***********************************************************

 

Cognizant Fresher Coding Assessment Practice Set

Format: 10 Coding Questions
Languages: Suitable for Python, Java, C++, or C
Suggested Time: 90 minutes

 

Section 1: Warm-up (Basics) – 5 Questions

1. Factorial of a Number

Write a function to compute the factorial of a given non-negative integer n.
Example Input: n = 5
Expected Output: 120

 

2. Check Palindrome

Write a function that checks if a given string is a palindrome.
Example Input: "radar"
Expected Output: True

 

3. Find the Maximum in a List/Array

Write a function to return the largest element in a given list or array.
Example Input: [12, 45, 23, 67, 34]
Expected Output: 67

 

4. Count Vowels in a String

Write a function to count the number of vowels (a, e, i, o, u) in a string.
Example Input: "Hello World"
Expected Output: 3

 

5. Sum of Digits

Write a function that takes a number and returns the sum of its digits.
Example Input: 1234
Expected Output: 10

 

Section 2: Problem Solving – 5 Questions

 

6. Fibonacci Series up to N Terms

Write a function to print the first n terms of the Fibonacci series.
Example Input: n = 6
Expected Output: 0 1 1 2 3 5

 

7. Find Missing Number in Array

Given n numbers in the range 1 to n+1, with one number missing, find it.
Input: [1, 2, 3, 5]
Expected Output: 4

 

8. Armstrong Number Checker

Write a function to check if a given number is an Armstrong number.
Example Input: 153
Expected Output: True

 

9. Remove Duplicates from a List

Write a function to remove duplicates from a list and return the unique elements.
Example Input: [1, 2, 2, 3, 4, 4, 5]
Expected Output: [1, 2, 3, 4, 5] (Order can vary)

 

10. Sort a List Without Built-in Sort

Write a function to sort an array using bubble sort (or any other sorting algorithm) without using the built-in sort function.
Example Input: [64, 25, 12, 22, 11]
Expected Output: [11, 12, 22, 25, 64]

 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Level: Medium to Hard

Duration: 90 minutes
Languages: Any (Python, Java, C++, C, etc.)
Recommended Environment: HackerRank / LeetCode / VS Code


1. Subarray with Given Sum (Sliding Window / Hashing)

Problem:
Given an array of positive integers and a target sum k, find the number of continuous subarrays whose sum equals k.

Input:

arr = [1, 1, 1], k = 2

Output:

2

Constraints:

  • Optimize beyond brute-force.
  • Use prefix sums or hashing for better performance.

2. Kth Largest Element (Heap/Sorting)

Problem:
Given an unsorted array, find the kth largest element in it.

Input:

arr = [3, 2, 1, 5, 6, 4], k = 2

Output:

5

Hints:

  • Use a min-heap (priority queue) or sort the array.

3. Valid Parentheses with Wildcards (*) – (Stack + Recursion / DP)

Problem:
Given a string containing '(', ')', and '*', determine if it's a valid parentheses string. The '*' can represent '(', ')', or an empty string.

Input:

"(*)"

Output:

True

Constraints:

  • Implement an efficient solution (not brute-force recursion).

4. Longest Substring Without Repeating Characters (Sliding Window)

Problem:
Given a string, find the length of the longest substring without repeating characters.

Input:

s = "abcabcbb"

Output:

3  // "abc"


5. Rotate Matrix 90 Degrees (In-place Array Manipulation)

Problem:
Rotate a n x n matrix by 90 degrees (clockwise), in-place.

Input:

[

 [1,2,3],

 [4,5,6],

 [7,8,9]

]

Output:

[

 [7,4,1],

 [8,5,2],

 [9,6,3]

]


6. Count Digit Occurrences (Recursion / Math)

Problem:
Count how many times digit 1 appears in the range from 1 to n.

Input:

n = 13

Output:

6  // (1, 10, 11, 12, 13)

Challenge:

  • Try solving without converting each number to string.
  • Use mathematical pattern-based logic.

7. Merge Intervals (Sorting + Logic)

Problem:
Given a collection of intervals, merge all overlapping intervals.

Input:

[[1,3],[2,6],[8,10],[15,18]]

Output:

[[1,6],[8,10],[15,18]]

Constraints:

  • You must return the merged intervals in sorted order.

8. Implement LRU Cache (Hash Map + Doubly Linked List)

Problem:
Design a data structure that follows the Least Recently Used (LRU) cache strategy.
It should support get() and put() operations in O(1) time.

Functionality:

  • get(key): Return value if key exists, else -1
  • put(key, value): Add or update the key, and evict the least recently used item if full

Hint:

  • Use a combination of a hash map and a doubly linked list.

9. Maximum Product Subarray (Kadane’s Variant)

Problem:
Given an array of integers (both +ve and -ve), find the contiguous subarray with the maximum product.

Input:

arr = [2,3,-2,4]

Output:

6  // [2,3]

Note:

  • Handle negative numbers carefully.

10. Nth Digit in Infinite Integer Sequence (Math, Binary Search)

Problem:
Find the nth digit in the sequence: 1234567891011121314…

Input:

n = 11

Output:

0  // 11th digit is '0' from number '10'

Constraints:

  • Avoid constructing the entire sequence.

Instructions for Candidates

  • Use any language you're comfortable with.
  • Focus on optimizing time and space complexity.
  • For questions 3, 6, 8, and 10, brute-force methods will likely time out in real assessments.
  • Document edge case handling where applicable.

 

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

Level: Hard to Complex
Duration: 120 minutes
Languages: Any (Python, Java, C++, etc.)
Objective: Assess core algorithmic thinking, optimization, and problem-solving under constraints.

 

Question 1: Minimum Window Substring (Sliding Window + Hash Map)

Problem:
Given two strings s and t, return the minimum window in s which will contain all the characters in t. If there is no such window, return an empty string.

Input:

s = "ADOBECODEBANC", t = "ABC"

Output:

"BANC"

Constraints:

  • Optimize beyond brute force (O(n^2) is not acceptable).
  • Use two-pointer sliding window with frequency maps.

 

Question 2: Expression Add Operators (Backtracking + DFS)

Problem:
Given a string that contains only digits and a target value, add binary operators (+, -, or *) between the digits so that the expression evaluates to the target.

Input:

num = "123", target = 6

Output:

["1+2+3", "1*2*3"]

Constraints:

  • Return all valid expressions.
  • Avoid using eval(). Simulate expressions manually using recursion.

 

Question 3: Skyline Problem (Heap + Sweep Line Algorithm)

Problem:
You are given an array of buildings represented by [start, end, height]. Return the skyline formed by these buildings.

Input:

[[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]

Output:

[[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]

Hints:

  • Use a max heap to track active buildings.
  • Sort and sweep through the x-axis.

 

Question 4: Word Ladder II (BFS + Backtracking)

Problem:
Given a start word, an end word, and a dictionary, find all shortest transformation sequences from start to end.

Each transformation must change one letter at a time, and all intermediate words must exist in the dictionary.

Input:

start = "hit", end = "cog", wordList = ["hot","dot","dog","lot","log","cog"]

Output:

[

  ["hit","hot","dot","dog","cog"],

  ["hit","hot","lot","log","cog"]

]

Hints:

  • Use BFS to find shortest path levels.
  • Use backtracking to build the paths.

 

Question 5: Trapping Rain Water II (Graph + Heap)

Problem:
Given a 2D elevation map, compute how much water it can trap after raining.

Input:

heightMap = [

  [1,4,3,1,3,2],

  [3,2,1,3,2,4],

  [2,3,3,2,3,1]

]

Output:

4

Hints:

  • Use BFS with a min-heap (priority queue).
  • Think in 3D and process outer boundaries first.

 

Question 6: Number of Digit One (Mathematical Pattern Recognition)

Problem:
Count the number of times digit '1' appears in all numbers from 1 to n.

Input:

n = 824883294

Output:

767944060

Hints:

  • Avoid looping from 1 to n (too slow).
  • Use mathematical formula + positional analysis.

 

Question 7: Hard Recursive Combination - All Valid K-Parenthesis Strings

Problem:
Given a number k, return all valid combinations of k types of parentheses.
Each type has a different bracket: (), {}, [].

Input:

k = 1

Output:

["(){}[]", "()[{}]", "(())[{}]", "{()[]}", etc.]

Hints:

  • Think of multi-type DFS generation.
  • Track individual stacks for each bracket type.

 

Question 8: Sudoku Solver (Backtracking + Constraint Propagation)

Problem:
Write a program to solve a Sudoku puzzle by filling the empty cells.

Input:
A 9x9 board with some digits and '.' as empty cells.

Constraints:

  • Use recursive backtracking with pruning.
  • Optional: Try applying constraint propagation to optimize.

 

Question 9: Kth Smallest Element in a Sorted Matrix (Heap + Binary Search)

Problem:
Given an n x n matrix where each row and column is sorted in ascending order, return the kth smallest element.

Input:

matrix = [

 [1, 5, 9],

 [10, 11, 13],

 [12, 13, 15]

], k = 8

Output:

13

Approaches:

  • Min-Heap (Heapify first elements of each row)
  • Binary Search over value range

 

Question 10: Distribute N Candies in K Baskets with Constraints (DP + Combinatorics)

Problem:
You have n candies and k baskets. You can place any number of candies in each basket, but no basket can have more than m candies. Count the number of ways to distribute.

Input:

n = 7, k = 3, m = 4

Output:

6

Constraints:

  • Use DP or recursive memoization.
  • Think of this as a bounded integer partition problem.

()()()()()()())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()(()()()()()()()()()()()()()()()(

 

 

Level: Advanced / Complex
Duration: 2 to 3 hours
Goal: Strengthen DSA mastery, algorithmic depth, optimization under constraints
Languages: Any (Python, Java, C++, etc.)
Expected Outcome: Crack top-tier coding interviews, even at a fresher level


1. Alien Dictionary (Topological Sort + Graph Construction)

Problem:
Given a sorted dictionary of an alien language, find the order of characters in that language.

Input:

words = ["baa", "abcd", "abca", "cab", "cad"]

Output:

"bdac"

Constraints:

  • Detect cycles in case of invalid dictionaries.
  • Requires building a graph + topological sort (Kahn's algorithm / DFS).

2. Maximum XOR of Two Numbers in an Array (Trie + Bitwise DP)

Problem:
Given an array of integers, find the maximum result of nums[i] ^ nums[j] for any i, j.

Input:

nums = [3, 10, 5, 25, 2, 8]

Output:

28  // 5 ^ 25

Constraints:

  • Must be solved in O(n) using a Trie of binary representations.

3. Count of Smaller Elements After Self (Modified Merge Sort / Binary Indexed Tree)

Problem:
For each element in an array, count the number of smaller elements that come after it.

Input:

[5, 2, 6, 1]

Output:

[2, 1, 1, 0]

Approach:

  • Use merge sort inversion count logic, or
  • Implement Fenwick Tree (BIT) for index compression

4. Serialize and Deserialize a Binary Tree (DFS / Recursion / Tree Building)

Problem:
Implement functions serialize(root) and deserialize(data) to convert a binary tree to a string and back.

Input Example:

[1,2,3,null,null,4,5]

Output:

Serialized: "1,2,null,null,3,4,null,null,5,null,null"

Constraints:

  • Must handle null nodes correctly.
  • Your deserialized tree must be identical to original.

5. Regular Expression Matching (Dynamic Programming + Backtracking)

Problem:
Implement regular expression matching with support for '.' and '*'.

Input:

s = "aab", p = "c*a*b"

Output:

True

Approach:

  • Requires 2D DP table and careful matching logic.

6. Minimum Cost to Split Array (DP + Partitioning)

Problem:
Given an array and a cost function that charges you cost = sum(part)^2 for each split part, find the minimum total cost to split the array into k parts.

Input:

arr = [1,2,3,4,5], k = 2

Output:

117  // Best split is [1,2,3] and [4,5]

Hint:

  • Use DP with prefix sums.
  • Requires partitioning optimization, maybe with Knuth’s Optimization.

7. Median in a Sliding Window (Multiset / Heaps + Deletion)

Problem:
Given an array nums and a window size k, return the median of each window.

Input:

nums = [1,3,-1,-3,5,3,6,7], k = 3

Output:

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

Approach:

  • Use two heaps (max + min).
  • Manage efficient removal of old elements.

8. Palindrome Pairs (Trie + String Manipulation)

Problem:
Given a list of unique words, find all pairs of distinct indices (i, j) such that words[i] + words[j] is a palindrome.

Input:

["abcd", "dcba", "lls", "s", "sssll"]

Output:

[[0,1],[1,0],[3,2],[2,4]]

Hint:

  • Use a Trie to check reverses efficiently.
  • Requires string manipulation + partitioning.

9. Dungeon Game (Reverse DP)

Problem:
You are in a dungeon grid with health points. Calculate the minimum initial health required to reach the bottom-right cell while only moving right or down.

Input:

[[-2,-3,3],[−5,−10,1],[10,30,-5]]

Output:

7

Approach:

  • Solve with bottom-up DP, keeping track of health points.

10. Paint House III (DP + Grouping + Pruning)

Problem:
You are given a list of houses with some already painted, and a cost matrix. Paint all houses with minimum cost such that there are exactly target neighborhoods.

Input:

houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3

Output:

9

Hint:

  • Use 3D DP: house index, last color, neighborhoods formed
  • Apply memoization with pruning

 

 

 

No comments:

Post a Comment