17 real HCL interview questions with full model answers — Coding. Drawn from the same verified bank ChannelPulse drills from (17 HCL questions in total).
17 HCL questions in the bank
1 categories covered
1 roles: Software Engineer
CodingEasyHCLSoftware Engineer
1. 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
Set pointers to the last valid elements of both arrays.
Set a write pointer to the last slot in the first array.
While the second array still has elements, compare the values at the two read pointers.
Write the larger value at the write pointer, then move the corresponding read pointer and the write pointer left.
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.
CodingEasyHCLSoftware Engineer
2. 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
Return False for negative integers.
Return False for positive integers ending in zero; zero itself is a palindrome.
Repeatedly move the last digit from the number to a reversed-half accumulator.
Stop when the accumulator has at least as many digits as the remaining number.
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.
CodingEasyHCLSoftware Engineer
3. 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
Create a dictionary mapping previously seen values to their indices.
For each element, compute the complement needed to reach the target.
If that complement is in the dictionary, return its stored index and the current index.
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.
CodingEasyHCLSoftware Engineer
4. 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
Initialize pointers at the start and end of the string.
Move the left pointer past non-alphanumeric characters.
Move the right pointer past non-alphanumeric characters.
Compare the lowercase forms of the characters at the pointers; return False if they differ.
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.
CodingEasyHCLSoftware Engineer
5. 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
Return False if the string has odd length.
Map each closing bracket to its matching opening bracket.
Scan the string from left to right.
Push opening brackets onto the stack.
For a closing bracket, return False if the stack is empty or its top does not match; otherwise pop.
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.
CodingEasyHCLSoftware Engineer
6. 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
Initialize the minimum price to a value larger than any price and the best profit to zero.
Visit each price in order.
Update the minimum price with the current price.
Check the profit from selling today and update the best profit.
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.
CodingEasyHCLSoftware Engineer
7. Missing Number (LeetCode)
Model answer
The task
Given an array of distinct integers drawn from the range 0 through n, return the one number in that range that is absent.
Key idea
The complete range has a known sum: n * (n + 1) // 2. Subtracting the array’s sum leaves the missing value, without needing to sort or store extra data.
Approach
Let n be the number of values in the array.
Calculate the expected sum of all integers from 0 through n.
Calculate the sum of the values actually present.
Return the difference. This also handles a missing value at either end of the range.
from typing import List
class Solution:
def missingNumber(self, nums: List[int]) -> int:
n = len(nums)
# The array contains n of the n + 1 values from 0 through n.
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum
Complexity:
Time: O(n), to sum the array.
Space: O(1), using only a fixed number of variables.
Common follow-ups
What if the values are sorted? Use binary search to find where the values stop matching their indices, for O(log n) time.
Can you avoid a sum that might overflow in a fixed-width integer language? XOR the values with all indices from 0 through n; equal values cancel, leaving the missing number.
What if duplicates are allowed or more than one number is missing? The sum difference alone is insufficient; use a frequency structure or adapt the task to the number of missing values.
What if the input must remain unchanged? This solution does not modify the array.
CodingEasyHCLSoftware Engineer
8. Valid Perfect Square (LeetCode)
Model answer
The task
Determine whether an integer is the square of another integer, without using a square-root function.
Key idea
Binary-search for a possible square root. Since squaring is increasing for nonnegative integers, compare each midpoint’s square with the target to decide which half to search next.
Approach
Return False for negative values and True for zero.
Search between 1 and the target.
Compute the midpoint’s square.
Return True if it equals the target; otherwise, discard the half that cannot contain the root.
If the search ends without a match, return False.
class Solution:
def isPerfectSquare(self, num: int) -> bool:
if num < 0:
return False
if num == 0:
return True
left, right = 1, num
while left <= right:
mid = left + (right - left) // 2
square = mid * mid
if square == num:
return True
if square < num:
left = mid + 1
else:
right = mid - 1
return False
Complexity:
Time: O(log n), because binary search halves the search range each iteration.
Space: O(1), using only a fixed number of variables.
Common follow-ups
How would you solve it with Newton’s method? Repeatedly improve a root estimate until it stabilizes, then check its square.
What changes in a language with fixed-width integers? Avoid overflow by comparing mid with num // mid.
What edge cases should be checked? Zero, one, negative values, and squares near the target.
CodingEasyHCLSoftware Engineer
9. Reverse String (LeetCode)
Model answer
The task
Reverse the sequence of characters in place. The method should modify the given list rather than create and return a reversed copy.
Key idea
Use two pointers, one at each end of the list. Swap their characters, then move both pointers inward until they meet or cross.
Approach
Set left to the first index and right to the last.
While left < right, swap the characters at those indices.
Advance left and decrease right.
Stop once the pointers meet or cross; the list has been reversed.
from typing import List
class Solution:
def reverseString(self, s: List[str]) -> None:
"""Reverse s in place."""
left = 0
right = len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
Complexity:
Time: O(n), where n is the number of characters; each character is involved in at most one swap.
Space: O(1), since the reversal uses only two index variables and swaps in place.
Common follow-ups
Reverse only a subrange: Initialize the pointers to the subrange’s endpoints and use the same swap loop.
Reverse an immutable string: Convert it to a mutable character list, reverse that list, then join it into a new string.
Handle Unicode grapheme clusters: Reverse grapheme clusters rather than code points, since a visible character can consist of multiple code points.
CodingMediumHCLSoftware Engineer
10. Palindromic Substrings (LeetCode)
Model answer
The task
Given a string, count how many of its substrings are palindromes. Count each substring by its position, so equal text at different positions contributes more than once.
Key idea
Every palindrome has a center: either one character or the gap between two characters. Expand outward from each possible center while the characters match, counting each palindrome found.
Approach
Initialize a counter for the palindromic substrings.
Visit each character position as an odd-length center.
Visit each gap between adjacent characters as an even-length center.
For each center, expand left and right while the characters match, adding one to the counter for each match.
Return the counter.
class Solution:
def countSubstrings(self, s: str) -> int:
count = 0
n = len(s)
def expand(left: int, right: int) -> int:
found = 0
# Every matching expansion forms another palindrome.
while left >= 0 and right < n and s[left] == s[right]:
found += 1
left -= 1
right += 1
return found
for center in range(n):
# Odd-length palindromes centered on one character.
count += expand(center, center)
# Even-length palindromes centered between characters.
count += expand(center, center + 1)
return count
Complexity:
Time: O(n²), since each of the O(n) centers can expand across O(n) characters.
Space: O(1), using only a counter and a few indices.
Common follow-ups
How would you find the longest palindromic substring? Track the longest span found during each expansion.
How would you count distinct palindrome values instead of occurrences? Store the distinct palindrome strings in a set; this can require O(n²) space.
Can this be solved with dynamic programming? Yes: record whether each interval is a palindrome based on its end characters and its inner interval, using O(n²) time and space.
CodingMediumHCLSoftware Engineer
11. Minimum Size Subarray Sum (LeetCode)
Model answer
The task
Given a target and an array of positive integers, find the shortest contiguous subarray whose sum is at least the target. Return 0 if no such subarray exists.
Key idea
Because every number is positive, extending a window can only increase its sum, and removing its leftmost number can only decrease it. Expand the right edge until the sum reaches the target, then shrink from the left while the window remains valid.
Approach
Initialize the left edge, running sum, and best length.
Move the right edge across the array, adding each value to the sum.
While the window sum meets the target, record its length and remove the leftmost value.
Return the best length, or 0 if no valid window was found.
class Solution:
def minSubArrayLen(self, target: int, nums: list[int]) -> int:
left = 0
window_sum = 0
best = len(nums) + 1
for right, value in enumerate(nums):
window_sum += value
# Shrink the window as much as possible while it remains valid.
while window_sum >= target:
best = min(best, right - left + 1)
window_sum -= nums[left]
left += 1
return 0 if best == len(nums) + 1 else best
Complexity:
Time: O(n), since each index enters and leaves the window at most once.
Space: O(1), using only a few variables.
Common follow-ups
How would you solve it with binary search? Build prefix sums, then binary-search for the earliest prefix reaching the target from each starting position, in O(n log n).
What if the array can contain negative numbers? This sliding-window method no longer works; use prefix sums with a monotonic deque for the shortest qualifying subarray.
Can you return the subarray’s indices as well as its length? Store the left and right indices whenever a shorter valid window is found.
CodingMediumHCLSoftware Engineer
12. Maximum Subarray (LeetCode)
Model answer
The task
Given an integer array, find the largest sum obtainable from a nonempty contiguous subarray. The array may contain only negative numbers.
Key idea
At each position, the best subarray ending there either starts at the current value or extends the best subarray ending just before it. Track that running best and the largest sum seen so far; this naturally handles all-negative arrays.
Approach
Initialize both the running sum and overall maximum to the first value.
Scan the remaining values from left to right.
For each value, either start a new subarray there or extend the previous one.
Update the overall maximum whenever the running sum improves.
Return the overall maximum.
from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
# The subarray must be nonempty, so start with the first element.
current_sum = best_sum = nums[0]
for value in nums[1:]:
# Either begin at this value or extend the prior subarray.
current_sum = max(value, current_sum + value)
best_sum = max(best_sum, current_sum)
return best_sum
Complexity:
Time: O(n), where n is the number of array elements; each is processed once.
Space: O(1), since only two running sums are stored.
Common follow-ups
How would you return the subarray’s start and end indices? Track the current start index and record both indices whenever the overall maximum improves.
What if the input can be empty? Define the desired empty-input result, then handle it before accessing the first element.
How does divide and conquer solve this? Recursively compute the best sum on each half, plus the best suffix on the left and prefix on the right; combine the three results.
CodingMediumHCLSoftware Engineer
13. Group Anagrams (LeetCode)
Model answer
The task
Partition the input strings into groups so that strings in the same group contain the same characters with the same frequencies. The order of the groups does not matter.
Key idea
Sort the characters of each string to create a canonical key. Anagrams produce the same key, so a hash table can collect them together.
Approach
Create a mapping from canonical keys to lists of original strings.
For each string, sort its characters and use the result as its key.
Append the string to the list for that key.
Return all grouped lists.
from collections import defaultdict
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
groups = defaultdict(list)
for word in strs:
# Anagrams have identical sorted-character representations.
key = "".join(sorted(word))
groups[key].append(word)
return list(groups.values())
Complexity:
Time: O(n · k log k), where n is the number of strings and k is the maximum string length.
Space: O(n · k) to store the grouped strings and their keys.
Common follow-ups
Can this be faster for a fixed alphabet? Use a character-frequency tuple as the key, computing it in O(k) per string.
Does this work with uppercase letters or Unicode? Yes; sorting characters works for any Python strings.
Can groups be returned in a deterministic order? Sort the groups, or their keys, before returning them.
What if memory is limited? Consider processing input in batches or grouping externally by canonical key.
CodingMediumHCLSoftware Engineer
14. Longest Substring Without Repeating Characters (LeetCode)
Model answer
The task
Find the length of the longest contiguous section of a string in which every character appears at most once.
Key idea
Maintain a sliding window with no repeated characters. When a character repeats within the window, move the left edge just past its previous occurrence.
Approach
Track each character’s most recent index in a dictionary.
Keep left as the window’s starting index and best as its longest length so far.
For each character, move left forward if its previous occurrence is inside the current window.
Record the character’s current index and update best using the window length.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
last_seen = {}
left = 0
best = 0
for right, char in enumerate(s):
# Skip past a repeated character if it is in the current window.
if char in last_seen and last_seen[char] >= left:
left = last_seen[char] + 1
last_seen[char] = right
best = max(best, right - left + 1)
return best
Complexity:
Time: O(n), because each character is processed once.
Space: O(k), where k is the number of distinct characters encountered.
Common follow-ups
Return the substring itself: store the best window’s start and end indices when updating best.
Handle a stream of characters: keep the same window state and process each arriving character incrementally.
Use a fixed-size character set: replace the dictionary with an array of last-seen indices.
CodingMediumHCLSoftware Engineer
15. Second Highest Salary (LeetCode)
Model answer
The task
Return the second-highest distinct salary from the Employee table. If fewer than two distinct salaries exist, the result should be NULL.
Key idea
Remove duplicate salaries, then select the value at rank two in descending order. A scalar subquery returns NULL when there is no second row.
Approach
Select distinct salary values.
Sort them from highest to lowest.
Skip the highest value and take the next one.
Return that scalar value under the required column name.
-- Return the second-highest distinct salary, or NULL if it does not exist.
SELECT (
SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1
) AS SecondHighestSalary;
Complexity:
Time: O(n log n) in the general case, due to deduplication and sorting.
Space: O(n) in the general case, for intermediate distinct values; an index may reduce work.
Common follow-ups
How would you return the top k distinct salaries? Use DISTINCT, descending order, and LIMIT with the desired count.
How can you express this with a window function? Rank distinct salaries with DENSE_RANK() and select rank 2.
What if ties should count as separate positions? Remove DISTINCT so duplicate salaries occupy separate rows.
CodingHardHCLSoftware Engineer
16. Trapping Rain Water (LeetCode)
Model answer
The task
Given an array of nonnegative bar heights, compute how much water remains trapped between the bars after rainfall. Each bar has unit width.
Key idea
Water above a position is limited by the shorter of the tallest bars to its left and right. With two pointers, process the side whose current height is lower: its boundary already determines the maximum water that position can hold, so no arrays of prefix and suffix maxima are needed.
Approach
Start pointers at both ends and track the greatest height seen from each side.
While the pointers have not crossed, compare their current heights.
If the left height is lower, update the left maximum and add any water above the left bar, then advance the left pointer.
Otherwise, do the symmetric operation on the right.
Return the accumulated water.
from typing import List
class Solution:
def trap(self, height: List[int]) -> int:
left, right = 0, len(height) - 1
left_max = right_max = 0
water = 0
while left < right:
if height[left] < height[right]:
# The right side is tall enough that the left maximum
# determines the water level at this position.
left_max = max(left_max, height[left])
water += left_max - height[left]
left += 1
else:
# Symmetrically, the right maximum determines this level.
right_max = max(right_max, height[right])
water += right_max - height[right]
right -= 1
return water
Complexity:
Time: O(n), because each pointer moves across the array at most once.
Space: O(1), because the algorithm uses only a fixed number of variables.
Common follow-ups
How can this be solved with dynamic programming? Precompute the maximum height to each position from the left and right, then sum the trapped water at each position.
How can a monotonic stack solve it? Keep indices of decreasing bar heights; when a taller bar arrives, pop a basin bottom and calculate the bounded layer.
What if bars have different widths? Track each bar’s width and use area rather than unit-width contributions; the boundary logic must account for the resulting horizontal spans.
CodingHardHCLSoftware Engineer
17. Department Top Three Salaries (LeetCode)
Model answer
The task
Return employees whose salary is among the three highest distinct salaries in their department. Include all employees tied at one of those salary levels.
Key idea
Use DENSE_RANK within each department, ordering salaries from highest to lowest. Unlike ROW_NUMBER, it gives equal salaries the same rank and does not skip ranks after ties.
Approach
Rank employees separately within each department by descending salary.
Use DENSE_RANK so each distinct salary level gets one rank.
Keep rows with rank at most three.
Join to the department table to return department names.
WITH ranked_employees AS (
SELECT
e.id,
e.name,
e.salary,
e.departmentId,
DENSE_RANK() OVER (
PARTITION BY e.departmentId
ORDER BY e.salary DESC
) AS salary_rank
FROM Employee AS e
)
SELECT
d.name AS Department,
r.name AS Employee,
r.salary AS Salary
FROM ranked_employees AS r
JOIN Department AS d
ON d.id = r.departmentId
WHERE r.salary_rank <= 3;
Complexity:
Time: O(n log n), for ordering employees within departments.
Space: O(n), for the ranked rows and window-function processing.
Common follow-ups
Return the top K distinct salary levels: Replace 3 with a parameter K.
Return exactly three employees per department: Use ROW_NUMBER instead, with a deterministic tie-breaker such as employee ID.
Include departments with no employees: Start from Department and use a LEFT JOIN; employee columns will be NULL for empty departments.
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.