Cognizant interview questions & answers

20 real Cognizant interview questions with full model answers — Coding. Drawn from the same verified bank ChannelPulse drills from (51 Cognizant questions in total).

CodingEasyCognizantSoftware Engineer

1. Find the Index of the First Occurrence in a String (LeetCode)

Model answer

The task

Given a text string and a pattern string, return the starting index of the pattern’s first occurrence in the text. Return -1 if it does not occur; an empty pattern matches at index 0.

Key idea

Use Knuth–Morris–Pratt (KMP). Its prefix table lets the search reuse information about matched characters instead of restarting from scratch after a mismatch.

Approach

  1. Build a prefix table for the pattern. At each position, it records the length of the longest proper prefix that is also a suffix.
  2. Scan the text while tracking how many pattern characters currently match.
  3. On a mismatch, use the prefix table to find the next viable match length.
  4. Return the match’s starting index when the entire pattern matches; otherwise return -1.
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if not needle:
            return 0

        # Build the longest-prefix-suffix table for needle.
        lps = [0] * len(needle)
        prefix_len = 0
        i = 1

        while i < len(needle):
            if needle[i] == needle[prefix_len]:
                prefix_len += 1
                lps[i] = prefix_len
                i += 1
            elif prefix_len > 0:
                prefix_len = lps[prefix_len - 1]
            else:
                i += 1

        # Search haystack without rechecking matched characters.
        text_i = 0
        pattern_i = 0

        while text_i < len(haystack):
            if haystack[text_i] == needle[pattern_i]:
                text_i += 1
                pattern_i += 1

                if pattern_i == len(needle):
                    return text_i - pattern_i
            elif pattern_i > 0:
                pattern_i = lps[pattern_i - 1]
            else:
                text_i += 1

        return -1

Complexity:

  • Time: O(n + m), where n and m are the text and pattern lengths.
  • Space: O(m), for the prefix table.

Common follow-ups

  • How would you handle many pattern searches in the same text? Build an index or use a multi-pattern algorithm such as Aho–Corasick.
  • What if the text arrives as a stream? Keep the KMP match state and prefix table between chunks.
  • How would you find all occurrences? After each full match, record its start and reset the pattern index using the final prefix-table value.
CodingEasyCognizantSoftware Engineer

2. Merge Sorted Array (LeetCode)

Model answer

The task

Combine two already sorted arrays into one sorted array, placing the result in the first array. The first array has enough spare capacity to hold all elements from both arrays.

Key idea

Fill the first array from right to left. Comparing the largest remaining elements avoids overwriting values in the first array that have not yet been processed.

Approach

  1. Set pointers to the last valid elements of both arrays.
  2. Set a write pointer to the last slot in the first array.
  3. While the second array still has elements, compare the values at the two read pointers.
  4. Write the larger value at the write pointer, then move the corresponding read pointer and the write pointer left.
  5. Any remaining elements from the second array are copied into the first. Remaining elements from the first are already in place.
class Solution:
    def merge(self, nums1: list[int], m: int, nums2: list[int], n: int) -> None:
        """Merge nums2 into nums1 in-place, keeping nums1 sorted."""
        i = m - 1          # Last initialized element in nums1
        j = n - 1          # Last element in nums2
        write = m + n - 1  # Last available position in nums1

        # Fill from the back so unread nums1 elements are not overwritten.
        while j >= 0:
            if i >= 0 and nums1[i] > nums2[j]:
                nums1[write] = nums1[i]
                i -= 1
            else:
                nums1[write] = nums2[j]
                j -= 1
            write -= 1

Complexity:

  • Time: O(m + n), since each element is considered at most once.
  • Space: O(1), because the merge modifies the first array directly.

Common follow-ups

  • What if the arrays are sorted in descending order? Reverse the comparison or adapt the traversal direction.
  • What if the result must go into a separate array? Use two forward pointers and allocate O(m + n) extra space.
  • What if either array is empty? The loop naturally handles it; if the second is empty, the first is already complete.
  • Why merge from the end? Writing from the front could overwrite unprocessed elements in the first array.
CodingEasyCognizantSoftware Engineer

3. Minimum Absolute Difference (LeetCode)

Model answer

The task

Given an integer array, return every pair of values whose absolute difference is as small as possible. Each pair should list its smaller value first.

Key idea

Sort the values. The smallest difference must occur between two neighbors in sorted order: any non-neighboring pair has at least one intervening value and cannot have a smaller gap. A single scan can find the minimum gap and collect all pairs that achieve it.

Approach

  1. Sort the array in ascending order.
  2. Scan adjacent values to find the smallest difference.
  3. Scan adjacent values again, adding each pair whose difference equals that minimum.
  4. Return the collected pairs; the sorted scan produces them in ascending order.
from typing import List

class Solution:
    def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
        values = sorted(arr)

        # Find the smallest gap between neighboring values.
        min_gap = min(
            values[i] - values[i - 1]
            for i in range(1, len(values))
        )

        # Collect every neighboring pair with that gap.
        pairs = []
        for i in range(1, len(values)):
            if values[i] - values[i - 1] == min_gap:
                pairs.append([values[i - 1], values[i]])

        return pairs

Complexity:

  • Time: O(n log n), dominated by sorting; the scans take O(n).
  • Space: O(n), for the sorted copy and the returned pairs.

Common follow-ups

  • Can this be done without sorting? Not generally in linear time for arbitrary integers; sorting gives the required order efficiently.
  • What if the input may be modified? Sort arr in place to avoid creating a separate sorted copy.
  • What if values can repeat? Adjacent equal values have gap zero; collect every adjacent pair attaining the minimum.
  • Why are non-neighboring pairs unnecessary? In sorted order, a value between two elements makes their difference at least as large as one of the neighboring gaps.
CodingEasyCognizantSoftware Engineer

4. Third Maximum Number (LeetCode)

Model answer

The task

Return the third-largest distinct value in the array. If there are fewer than three distinct values, return the largest.

Key idea

Keep only the three largest distinct values seen so far, in descending order. Since this collection never has more than three elements, updating it takes constant time per input value.

Approach

  1. Start with an empty list of the largest distinct values.
  2. For each value, skip it if it is already in the list.
  3. Add it if fewer than three values are stored, or if it is larger than the current third-largest.
  4. Sort the small list in descending order after an insertion.
  5. Return the third value if available; otherwise return the largest.
from typing import List

class Solution:
    def thirdMax(self, nums: List[int]) -> int:
        top_three = []

        for value in nums:
            # Only distinct values count toward the ranking.
            if value in top_three:
                continue

            if len(top_three) < 3:
                top_three.append(value)
            elif value > top_three[2]:
                top_three[2] = value
            else:
                continue

            # The list has at most three elements.
            top_three.sort(reverse=True)

        # Fall back to the maximum when there are fewer than three
        # distinct values.
        return top_three[2] if len(top_three) == 3 else top_three[0]

Complexity:

  • Time: O(n), since each value requires only constant work on a list of at most three elements.
  • Space: O(1), since the list stores at most three values.

Common follow-ups

  • How would you find the kth-largest distinct value? Keep the largest k distinct values, or use a heap when k is large.
  • How would you handle a stream of values? Maintain the same bounded set as values arrive.
  • What if duplicates should count? Remove the distinct-value check so repeated values participate in the ranking.
CodingEasyCognizantSoftware Engineer

5. Palindrome Number (LeetCode)

Model answer

The task

Determine whether an integer reads the same from left to right and right to left. Negative values are not palindromes.

Key idea

Reverse only the last half of the digits, then compare it with the remaining first half. This avoids converting to a string and keeps the extra space constant.

Approach

  1. Return False for negative integers.
  2. Return False for positive integers ending in zero; zero itself is a palindrome.
  3. Repeatedly move the last digit from the number to a reversed-half accumulator.
  4. Stop when the accumulator has at least as many digits as the remaining number.
  5. Compare the halves directly for even digit counts, or discard the middle digit for odd counts.
class Solution:
    def isPalindrome(self, x: int) -> bool:
        # Negative numbers have a leading minus sign, so they cannot be palindromes.
        if x < 0:
            return False

        # A positive number ending in zero would need a leading zero to be palindromic.
        if x != 0 and x % 10 == 0:
            return False

        reversed_half = 0

        # Move digits until the reversed half is at least as long as the remaining half.
        while x > reversed_half:
            reversed_half = reversed_half * 10 + x % 10
            x //= 10

        # For an odd number of digits, ignore the middle digit.
        return x == reversed_half or x == reversed_half // 10

Complexity:

  • Time: O(log₁₀ n), for processing the digits of the number.
  • Space: O(1), using only a few integer variables.

Common follow-ups

  • How would you check a palindrome by converting to a string? Compare symmetric characters, using O(log n) extra space.
  • How would you avoid integer overflow in a fixed-width language? Reversing only half the digits keeps the accumulator bounded.
  • What about zero and numbers ending in zero? Zero is palindromic; other numbers ending in zero are not.
CodingEasyCognizantSoftware Engineer

6. Two Sum (LeetCode)

Model answer

The task

Given a list of integers and a target, return the indices of two distinct elements whose values add up to the target. The usual version guarantees a valid pair.

Key idea

As we scan the list, store each value’s index in a hash table. For the current value, check whether its needed complement has already appeared; this finds a pair in one pass.

Approach

  1. Create a dictionary mapping previously seen values to their indices.
  2. For each element, compute the complement needed to reach the target.
  3. If that complement is in the dictionary, return its stored index and the current index.
  4. Otherwise, store the current value and index, then continue.
from typing import List

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # Map each value already visited to its index.
        seen = {}

        for index, value in enumerate(nums):
            complement = target - value

            # A match must come from an earlier, distinct element.
            if complement in seen:
                return [seen[complement], index]

            seen[value] = index

        # The standard problem guarantees a solution.
        raise ValueError("No two elements sum to the target")

Complexity:

  • Time: O(n), where n is the number of elements; each lookup and insertion is O(1) on average.
  • Space: O(n), for the dictionary of values seen so far.

Common follow-ups

  • What if there may be multiple valid pairs? Return the first pair found, or keep searching and collect pairs according to the required output rules.
  • What if the input is sorted? Use two pointers from opposite ends for O(1) extra space; preserve original indices if those are required.
  • What if values repeat? The dictionary stores indices, and checking before insertion ensures the current element is not paired with itself.
CodingEasyCognizantSoftware Engineer

7. Valid Palindrome (LeetCode)

Model answer

The task

Determine whether a string reads the same forward and backward after disregarding characters that are not letters or digits and treating uppercase and lowercase as equivalent.

Key idea

Compare characters from both ends, skipping anything that should be ignored. If every remaining pair matches, the string is a palindrome.

Approach

  1. Initialize pointers at the start and end of the string.
  2. Move the left pointer past non-alphanumeric characters.
  3. Move the right pointer past non-alphanumeric characters.
  4. Compare the lowercase forms of the characters at the pointers; return False if they differ.
  5. Move both pointers inward and continue. If they meet or cross, return True.
class Solution:
    def isPalindrome(self, s: str) -> bool:
        left, right = 0, len(s) - 1

        while left < right:
            # Ignore characters that are not letters or digits.
            while left < right and not s[left].isalnum():
                left += 1
            while left < right and not s[right].isalnum():
                right -= 1

            # Compare without regard to letter case.
            if s[left].lower() != s[right].lower():
                return False

            left += 1
            right -= 1

        return True

Complexity:

  • Time: O(n), where n is the string length; each pointer moves only inward.
  • Space: O(1), since the comparisons use no additional data structure.

Common follow-ups

  • What if the input contains no letters or digits? It is considered a palindrome, since there are no mismatching characters.
  • Can you avoid creating a normalized copy of the string? Yes; the two-pointer scan uses constant extra space.
  • How would you handle Unicode normalization? Normalize the string first if canonically equivalent characters should compare as equal; that may require additional space.
CodingEasyCognizantSoftware Engineer

8. Valid Parentheses (LeetCode)

Model answer

The task

Determine whether a string of opening and closing round, square, and curly brackets is correctly nested and matched. Return a boolean.

Key idea

A closing bracket must match the most recent unmatched opening bracket. A stack captures that order: push openings, and check each closing bracket against the stack’s top.

Approach

  1. Return False if the string has odd length.
  2. Map each closing bracket to its matching opening bracket.
  3. Scan the string from left to right.
  4. Push opening brackets onto the stack.
  5. For a closing bracket, return False if the stack is empty or its top does not match; otherwise pop.
  6. Return True only if the stack is empty after the scan.
class Solution:
    def isValid(self, s: str) -> bool:
        pairs = {")": "(", "]": "[", "}": "{"}
        openings = set(pairs.values())
        stack = []

        for char in s:
            if char in openings:
                stack.append(char)
            else:
                # A closing bracket must match the latest unmatched opening.
                if not stack or stack[-1] != pairs.get(char):
                    return False
                stack.pop()

        # Unmatched opening brackets make the sequence invalid.
        return not stack

Complexity:

  • Time: O(n), where n is the string length; each character is processed once.
  • Space: O(n) in the worst case, when all characters are opening brackets.

Common follow-ups

  • How would you support additional bracket types? Add their matching pairs to the map.
  • Can you stop early? Yes; return False as soon as a closing bracket mismatches or has no opening bracket.
  • What if the input includes non-bracket characters? Define how to handle them, then either ignore them or reject them during the scan.
CodingEasyCognizantSoftware Engineer

9. Remove Duplicates from Sorted Array (LeetCode)

Model answer

The task

Given a sorted list of integers, modify it in place so each distinct value appears once in the front. Return the length of that unique prefix.

Key idea

Because the values are sorted, duplicates are adjacent. Keep a read pointer to scan the list and a write pointer for the next position where a new value belongs.

Approach

  1. If the list is empty, return 0.
  2. Start the write pointer at 1, since the first value is already unique.
  3. Scan from left to right.
  4. When the current value differs from the last value written, copy it to the write position and advance the pointer.
  5. Return the write pointer as the unique-prefix length.
from typing import List

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if not nums:
            return 0

        write = 1

        # Copy each newly encountered value into the unique prefix.
        for read in range(1, len(nums)):
            if nums[read] != nums[write - 1]:
                nums[write] = nums[read]
                write += 1

        return write

Complexity:

  • Time: O(n), where n is the length of the list.
  • Space: O(1), since the list is modified in place using only a fixed number of variables.

Common follow-ups

  • What if the list is not sorted? Use a set to track seen values while compacting unique values in their original order.
  • What if each value may appear at most twice? Write a value when fewer than two values have been written, or when it differs from the value two positions back.
  • What if the list is very large and cannot fit in memory? Process sorted chunks while carrying the last value across chunk boundaries.
CodingEasyCognizantSoftware Engineer

10. Linked List Cycle (LeetCode)

Model answer

The task

Determine whether a singly linked list eventually revisits a node, forming a cycle.

Key idea

Move two pointers through the list at different speeds. If a cycle exists, the faster pointer eventually catches the slower one; if the fast pointer reaches the end, the list is acyclic.

Approach

  1. Initialize both pointers at the list head.
  2. Advance the slow pointer by one node and the fast pointer by two.
  3. If the fast pointer or its next node is None, return False.
  4. If the pointers meet, return True.
from typing import Optional

class Solution:
    def hasCycle(self, head: Optional["ListNode"]) -> bool:
        # The slow pointer moves one step at a time.
        slow = head
        # The fast pointer moves two steps at a time.
        fast = head

        while fast is not None and fast.next is not None:
            slow = slow.next
            fast = fast.next.next

            if slow is fast:
                return True

        return False

Complexity:

  • Time: O(n), where n is the number of nodes visited before the pointers meet or the list ends.
  • Space: O(1), because only two pointers are used.

Common follow-ups

  • How could you solve it using a hash set? Record visited node identities; a repeated identity means there is a cycle, using O(n) extra space.
  • How can you find the cycle’s starting node? After the pointers meet, reset one to the head and move both one step at a time; their next meeting is the start.
  • How can you find the cycle’s length? Keep one pointer at the meeting node and advance another until it returns, counting steps.
CodingEasyCognizantSoftware Engineer

11. Best Time to Buy and Sell Stock (LeetCode)

Model answer

The task

Given daily stock prices, find the greatest profit possible from one buy followed by one later sale. If no sale would make money, return zero.

Key idea

As we scan the prices, keep the lowest price seen so far. Treat each current price as a possible sale and update the best profit using the difference from that minimum.

Approach

  1. Initialize the minimum price to a value larger than any price and the best profit to zero.
  2. Visit each price in order.
  3. Update the minimum price with the current price.
  4. Check the profit from selling today and update the best profit.
  5. Return the best profit.
class Solution:
    def maxProfit(self, prices: list[int]) -> int:
        min_price = float("inf")
        best_profit = 0

        for price in prices:
            # The current price can be a new best day to buy.
            min_price = min(min_price, price)

            # Or it can be the day to sell after the cheapest earlier buy.
            best_profit = max(best_profit, price - min_price)

        return best_profit

Complexity:

  • Time: O(n), where n is the number of prices; each is processed once.
  • Space: O(1), since only a few variables are stored.

Common follow-ups

  • What if multiple buy-and-sell transactions are allowed? Sum the gains from every adjacent price increase.
  • What if a transaction fee is charged? Track the best holding and non-holding profits, incorporating the fee when selling.
  • What if at most k transactions are allowed? Use dynamic programming over the number of completed transactions and whether a share is currently held.
CodingEasyCognizantSoftware Engineer

12. Majority Element (LeetCode)

Model answer

The task

Given an integer array with a value appearing more than half the time, return that value.

Key idea

Use Boyer–Moore majority vote: pair off different values, which cannot eliminate the majority completely. Track a candidate and a balance; the majority remains the candidate after one pass.

Approach

  1. Start with no candidate and a zero balance.
  2. For each value, choose it as the candidate if the balance is zero.
  3. Add one if it matches the candidate; otherwise subtract one.
  4. Return the final candidate.
class Solution:
    def majorityElement(self, nums: list[int]) -> int:
        candidate = None
        balance = 0

        for value in nums:
            if balance == 0:
                candidate = value

            if value == candidate:
                balance += 1
            else:
                balance -= 1

        # A majority is guaranteed to exist, so the final candidate is the answer.
        return candidate

Complexity:

  • Time: O(n), for one pass through the array.
  • Space: O(1), using only a candidate and a counter.

Common follow-ups

  • What if a majority is not guaranteed? Run a second pass to count the candidate and check whether its frequency exceeds half the array length.
  • How would you find values occurring more than one-third of the time? Track up to two candidates with Boyer–Moore’s generalized voting method, then verify their counts.
  • Can sorting solve it? Yes. Sort the array; the majority must occupy the middle position, giving O(n log n) time and typically extra space depending on the sort.
CodingEasyCognizantSoftware Engineer

13. Combine Two Tables (LeetCode)

Model answer

The task

Return each person’s first and last name along with their city and state, when an address is available. People without a matching address must still appear, with NULL for the address fields.

Key idea

Use a LEFT JOIN from Person to Address on PersonId. This keeps every person in the result, whether or not a matching address exists.

Approach

  1. Start with Person so the result includes every person.
  2. Left-join Address using the shared PersonId.
  3. Select the requested name and address columns.
  4. Do not filter on address columns, since that could remove people without addresses.
-- Return all people, including those without a matching address.
SELECT
    p.FirstName,
    p.LastName,
    a.City,
    a.State
FROM Person AS p
LEFT JOIN Address AS a
    ON p.PersonId = a.PersonId;

Complexity:

  • Time: O(P + A) on average with a hash join, where P and A are the row counts; the database may use a different plan.
  • Space: O(P + A) for a hash-based join; auxiliary memory depends on the database’s execution plan.

Common follow-ups

  • What changes if only people with addresses should be returned? Use an INNER JOIN.
  • What if a person can have multiple addresses? The join returns one row per matching address; define a rule or aggregate if only one row per person is wanted.
  • How can the join be supported efficiently? An index on Address.PersonId can help, especially for indexed nested-loop plans.
  • Why not filter out NULL cities? Such a filter would also exclude people without a matching address.
CodingEasyCognizantSoftware Engineer

14. Single Number (LeetCode)

Model answer

The task

Given an integer array in which every value appears twice except for one value that appears once, return the value that appears only once.

Key idea

XOR cancels pairs: x ^ x is zero, and XOR with zero leaves a value unchanged. Since XOR is also associative and commutative, the order of the array does not matter.

Approach

  1. Initialize an accumulator to zero.
  2. XOR each array value into the accumulator.
  3. After all pairs cancel, the accumulator contains the unpaired value.
  4. Return it.
class Solution:
    def singleNumber(self, nums: list[int]) -> int:
        # Paired values cancel under XOR.
        result = 0

        for value in nums:
            result ^= value

        return result

Complexity:

  • Time: O(n), where n is the number of array elements; each value is processed once.
  • Space: O(1), since the algorithm uses only one accumulator, regardless of the array size.

Common follow-ups

  • What if every value appears three times except one? Use bit counts across all values, keeping each count modulo three; the remaining bits form the unique value.
  • What if two values appear once and all others appear twice? XOR all values to get the XOR of the two unique values, then use a set bit to divide values into two groups.
  • Does the order of the array matter? No. XOR is associative and commutative, so the same result is produced for any order.
  • Can this be solved without modifying the input? Yes. The algorithm only reads the array and stores its running XOR.
CodingEasyCognizantSoftware Engineer

15. Move Zeroes (LeetCode)

Model answer

The task

Rearrange an integer array in place so all zeroes come after the nonzero values. Keep the nonzero values in their original relative order.

Key idea

Use a write pointer to mark where the next nonzero value belongs. Scan the array once, swapping each nonzero value into that position; this keeps the nonzero values stable and uses constant extra space.

Approach

  1. Set write to the first available position for a nonzero value.
  2. Scan each index from left to right.
  3. When a nonzero value is found, swap it with the value at write.
  4. Advance write after each nonzero value.
  5. Once the scan ends, all remaining positions contain zeroes.
from typing import List

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        # The next nonzero value belongs at index write.
        write = 0

        for read in range(len(nums)):
            if nums[read] != 0:
                nums[write], nums[read] = nums[read], nums[write]
                write += 1

Complexity:

  • Time: O(n), where n is the array length; each value is examined once.
  • Space: O(1), since rearrangement is done in place.

Common follow-ups

  • What if relative order does not matter? Partitioning zeroes and nonzeroes can be done with two pointers, potentially with fewer assignments.
  • Can you reduce unnecessary writes? Swap only when read != write; this avoids self-swaps.
  • What if the input is a linked list? Relink nonzero nodes in their original order, then append the zero-valued nodes.
CodingEasyCognizantSoftware Engineer

16. Climbing Stairs (LeetCode)

Model answer

The task

Count how many distinct ways there are to reach the top of a staircase with n steps when each move advances either one or two steps.

Key idea

To reach step i, the last move must come from step i - 1 or i - 2. Thus the number of ways to reach i is the sum of the ways to reach those two earlier steps. Only the previous two counts are needed, so there is no need to store a full table.

Approach

  1. Set the number of ways to reach step 0 to 1, representing the single empty sequence of moves.
  2. Set the number of ways to reach step 1 to 1.
  3. For each step from 2 through n, add the counts for the preceding two steps.
  4. Return the count for step n.
class Solution:
    def climbStairs(self, n: int) -> int:
        # Ways to reach steps 0 and 1.
        two_back = 1
        one_back = 1

        # Build the count using the two preceding results.
        for _ in range(2, n + 1):
            current = two_back + one_back
            two_back = one_back
            one_back = current

        return one_back

Complexity:

  • Time: O(n), since each step is processed once.
  • Space: O(1), since only two prior counts are retained.

Common follow-ups

  • What if each move can advance 1, 2, or 3 steps? Sum the counts for the previous three steps.
  • What if the result must be returned modulo a number? Apply the modulus after each addition.
  • What if some steps are forbidden? Set their ways count to zero and use dynamic programming for the allowed steps.
CodingEasyCognizantSoftware Engineer

17. Rising Temperature (LeetCode)

Model answer

The task

Find each weather record whose temperature is higher than the temperature recorded on the immediately preceding calendar day. Return the IDs of those records.

Key idea

Join the table to itself, matching each record with the record dated exactly one day earlier. Comparing only adjacent rows would be incorrect because dates may have gaps.

Approach

  1. Treat one copy of the table as the current day and another as the previous day.
  2. Join them where the current date is one day after the previous date.
  3. Keep pairs where the current temperature is higher.
  4. Return the current record’s ID.
SELECT current_day.id AS Id
FROM Weather AS current_day
JOIN Weather AS previous_day
  ON current_day.recordDate = DATE_ADD(previous_day.recordDate, INTERVAL 1 DAY)
WHERE current_day.temperature > previous_day.temperature;

Complexity:

  • Time: O(n log n) with an index on recordDate; the exact cost depends on the database’s query plan.
  • Space: O(1) auxiliary space, excluding space used for the result and any database join workspace.

Common follow-ups

  • What if there are missing dates? The exact one-day join naturally skips dates without a prior-day record.
  • How could this perform better on a large table? Add an index on recordDate and inspect the database’s execution plan.
  • How would you adapt this for another SQL dialect? Replace DATE_ADD with that dialect’s date arithmetic, such as a one-day interval expression.
CodingEasyCognizantSoftware Engineer

18. Count Subarrays of Length Three With a Condition (LeetCode)

Model answer

The task

Count contiguous groups of three numbers whose middle number is the average of the first and third.

Key idea

Check each possible group of three once. The average condition can be tested using integer arithmetic: the first and third numbers must sum to twice the middle number.

Approach

  1. Initialize a counter to zero.
  2. Iterate over each index that can be the middle of a group of three.
  3. Compare the sum of its neighbors with twice the middle value.
  4. Increment the counter when they match, then return it.
from typing import List

class Solution:
    def countSubarrays(self, nums: List[int]) -> int:
        count = 0

        # Treat each index from 1 onward as the middle of a length-three group.
        for middle in range(1, len(nums) - 1):
            if nums[middle - 1] + nums[middle + 1] == 2 * nums[middle]:
                count += 1

        return count

Complexity:

  • Time: O(n), since each possible group is checked once.
  • Space: O(1), using only a counter and loop index.

Common follow-ups

  • What if the required group length is larger? Iterate over all valid windows and check the specified condition for each.
  • What if the condition uses floating-point averages? Compare the sum to twice the middle value to avoid floating-point arithmetic.
  • Can the input be modified? No modification is needed; the scan only reads the values.
CodingEasyCognizantSoftware Engineer

19. Valid Anagram (LeetCode)

Model answer

The task

Determine whether two strings contain the same characters with the same frequencies, regardless of order.

Key idea

Anagrams have identical character counts. Count the characters in each string and compare the resulting frequency maps.

Approach

  1. If the strings have different lengths, return False.
  2. Build a frequency map for each string.
  3. Return whether the maps are equal.
from collections import Counter

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        # Different lengths cannot have matching character counts.
        if len(s) != len(t):
            return False

        # Anagrams have exactly the same character frequencies.
        return Counter(s) == Counter(t)

Complexity:

  • Time: O(n), where n is the length of either string; counting and comparison are linear.
  • Space: O(k), where k is the number of distinct characters stored in the frequency maps.

Common follow-ups

  • Can you do this without two maps? Update one frequency map using s, then decrement counts using t; verify all counts return to zero.
  • What if the input is guaranteed to contain only lowercase English letters? Use a fixed-size array of 26 counters instead of maps.
  • What if sorting is allowed? Sort both strings and compare them; this takes O(n log n) time.
CodingEasyCognizantSoftware Engineer

20. Find the Highest Altitude (LeetCode)

Model answer

The task

Given the altitude changes between consecutive points on a route, find the greatest altitude reached. The route starts at altitude zero.

Key idea

Each altitude is a prefix sum of the changes, with the starting altitude zero included. Track the running sum and its maximum as you process the array.

Approach

  1. Initialize the current altitude and highest altitude to zero.
  2. For each change, add it to the current altitude.
  3. Update the highest altitude if the current altitude is greater.
  4. Return the highest altitude.
class Solution:
    def largestAltitude(self, gain: list[int]) -> int:
        altitude = 0
        highest = 0  # Include the starting altitude.

        for change in gain:
            altitude += change
            highest = max(highest, altitude)

        return highest

Complexity:

  • Time: O(n), where n is the number of altitude changes.
  • Space: O(1), since only a fixed number of variables are used.

Common follow-ups

  • What if the route starts at altitude s? Initialize both variables to s.
  • How would you return the index of the highest point? Track the prefix-sum index whenever the maximum increases.
  • Can the altitude changes arrive as a stream? Yes; update the running sum and maximum for each change as it arrives.

Practice these out loud, don't memorise them

Reading an answer is not the same as being able to give one under pressure. ChannelPulse plays the interviewer, asks the follow-ups, and scores each answer with feedback and a model answer so you can hear the gap between what you said and what lands.

Get ChannelPulse Browse all questions