Table of content:
- Overview of HCL Coding Questions
- HCL Coding Interview Questions
- Coding Problem Statements with Solutions
- Conclusion
- Frequently Asked Questions (FAQs)
HCL Coding Questions: Coding Pattern with Questions & Solutions

HCL coding questions in placement exams typically test fundamental programming knowledge, problem-solving skills, and the candidate's ability to write efficient and logical code. These questions are commonly part of the technical assessment phase and may be asked in an online test format.
Overview of HCL Coding Questions
Question Type | Description | Sample Question | Skills Assessed |
---|---|---|---|
Basic Programming | Tests knowledge of programming fundamentals such as variables, loops, and conditions. | Write a program to find the factorial of a number. | Control structures, loops, syntax |
Data Structures | Requires the use of data structures like arrays, lists, stacks, queues, and trees to solve problems. | Given an array, find the maximum difference between two elements. | Array manipulation, indexing |
String Manipulation | Involves working with strings, including operations like reversing, substring finding, and pattern matching. | Write a function to check if a string is a palindrome. | String handling, logic |
Sorting and Searching | Tests the ability to implement or apply sorting and searching algorithms for given datasets. | Implement a function to sort an array using the bubble sort algorithm. | Algorithm implementation |
Mathematical Problems | Tests the application of mathematical formulas, number theory, and logical math operations. | Find the GCD of two numbers. | Math operations, efficiency |
Dynamic Programming | Advanced questions involving optimization problems are commonly used in more challenging coding assessments. | Write a program to find the nth Fibonacci number using dynamic programming. | Recursion, efficiency, optimization |
Object-Oriented Concepts | Often includes questions about classes, inheritance, polymorphism, and encapsulation in OOP languages. | Create a class in Python that models a bank account with deposit and withdrawal methods. | Object-oriented design, encapsulation |
Common Languages for Coding Questions
-
Java and Python are often preferred for coding questions due to their simplicity in syntax and versatility.
-
C++ is also common for data structure-related questions, especially when dealing with memory management or efficiency.
Enhance your coding skills by practising coding questions across various levels. Click here to start your coding journey and master programming!
HCL Coding Interview Questions
HCL coding interviews typically focus on assessing the candidate's problem-solving approach, programming knowledge, and ability to optimize solutions. The interview questions often involve practical coding challenges along with discussions on algorithms and data structures. Here’s a breakdown of common question types and expectations:
Question Category | Description | Sample Question | Key Points in Answering |
---|---|---|---|
Algorithm Design | Design algorithms to solve specific problems efficiently. | Design an algorithm to merge two sorted arrays. | Focus on time complexity and optimization. |
Array and String Problems | Frequently used for assessing understanding of data indexing, manipulation, and storage. | Reverse an array in place without using extra space. | Provide clear steps and consider edge cases. |
Linked Lists | Tests knowledge of pointer-based data structures and traversal techniques. | Detect if a linked list has a cycle and remove it if found. | Explain concepts of pointers and traversal. |
Recursion and Backtracking | Used for solving complex problems that require trial and error, often in combinatorial contexts. | Write a recursive function to solve the N-Queens problem. | Explain base cases and recursive calls. |
Database-Related Coding | Tests SQL knowledge, especially for software development roles that involve database management. | Write an SQL query to retrieve the top 3 highest-paid employees. | Focus on efficient SQL joins and functions. |
Binary Trees and Graphs | Common for technical roles requiring an understanding of hierarchical or networked data structures. | Write a function to perform a breadth-first traversal on a binary tree. | Explain tree traversal techniques. |
Dynamic Programming | Tests optimization techniques using memoization or bottom-up approaches. | Solve the knapsack problem using dynamic programming. | Emphasize time complexity improvements. |
Detailed Breakdown of HCL Coding Interview Phases
Interview Phase | Description | Tips for Success |
---|---|---|
Online Coding Round | An online test where candidates solve programming questions in a limited time, typically via a coding platform. | Practice coding on platforms like HackerRank or LeetCode; focus on completing problems accurately within time. |
Technical Interview | In-person or virtual interviews where candidates are asked to solve coding problems on a whiteboard or shared screen. | Explain thought processes clearly, use efficient algorithms and write clean, readable code. |
Coding Challenge | Some roles involve live coding with a team or interviewer, emphasizing real-time problem-solving skills. | Stay calm, communicate clearly, and break down problems into smaller tasks for clarity. |
Examples of HCL Coding Interview Questions with Explanation
-
Problem: Write a program to find the second largest element in an array.
-
Explanation: Candidates should sort the array or maintain two variables to track the largest and second-largest elements, ensuring that the solution is efficient.
-
-
Problem: Implement a function to check if two strings are anagrams of each other.
-
Explanation: A good solution would involve sorting both strings and comparing them or using hash maps to count character frequencies.
-
-
Problem: Given a linked list, write a function to reverse it.
-
Explanation: Candidates should be familiar with pointer manipulation and understand iterative or recursive solutions for reversing linked lists.
-
-
Problem: Write a recursive function to calculate the factorial of a number.
-
Explanation: Demonstrates understanding of recursion with a base case and recursive call.
-
-
Problem: Create a SQL query to find employees earning more than the average salary in each department.
-
Explanation: Tests SQL skills, especially with aggregate functions and GROUP BY.
-
Coding Problem Statements with Solutions
Problem Statement 1
Rahul has an integer array called 'arr' of length N containing unique values. He wants to create a balanced tree where each parent node has smaller valued nodes on its left and larger valued nodes on its right. This balanced tree should ensure that the depth of the two subtrees for every node doesn't differ by more than one.
Your task is to assist him in creating this type of tree.
The output contains N lines denoting the pre-order traversal of nodes. If the left child of the node contains not null value then print the value else print a dot(.) , a similar process for the right child also. Each right child value is separated from the node by “->” sign and each left child by a left arrow sign
Input Format
First line contains an integer N representing the size of the array arr
The second line contains N unique space-separated integers representing the elements of the array arr
Output Format
The output contains N lines denoting the pre-order traversal of nodes. If the left child of the node contains not null value then print the value else print a dot(.) , a similar process for the right child also. Each right child value is separated from the node by “->” sign and each left child by a left arrow sign
Constraints
1<= N <= 10^5
1 <= arr[i] <= 10^9
Solution 1: Python
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
# Function to construct a balanced BST from the sorted array
def construct(arr, lo, hi):
    if lo > hi:
        return None
    # Pick the middle element to make the current node
    mid = hi - ((hi - lo) // 2)
    node = Node(arr[mid])
    # Recursively construct the left and right subtrees
    node.left = construct(arr, lo, mid - 1)
    node.right = construct(arr, mid + 1, hi)
    return node
# Function to display the tree in the required format (pre-order traversal)
def display(node):
    if node is None:
        return
    # Format the current node and its left and right children
    str_val = ""
    str_val += "." if node.left is None else str(node.left.data)
    str_val += " <- " + str(node.data) + " -> "
    str_val += "." if node.right is None else str(node.right.data)
    print(str_val)
    # Recursively display the left and right subtrees
    display(node.left)
    display(node.right)
if __name__ == "__main__":
    # Input size of the array
    n = int(input())
    # Input the array
    arr = list(map(int, input().split()))
    # Sort the array to ensure it's in ascending order
    arr.sort()
    # Construct the balanced BST
    root = construct(arr, 0, len(arr) - 1)
    # Display the tree in the required format
    display(root)
Solution 2: Java
import java.io.*;
import java.util.*;
public class Main {
    public static class Node {
        int data;
        Node left;
        Node right;
        Node(int data, Node left, Node right) {
            this.data = data;
            this.left = left;
            this.right = right;
        }
    }
    public static Node construct(int[] arr,int lo, int hi) {
        if(lo>hi)return null;
        int mid = hi-((hi-lo)/2);
        int data = arr[mid];
        Node left = construct(arr,lo,mid-1);
        Node right = construct(arr,mid+1,hi);
        Node node = new Node(data, left, right);
        return node;
    }
    public static void display(Node node) {
        if (node == null) {
            return;
        }
String str = "";
     str += node.left == null ? "." : node.left.data + "";
        str += " <- " + node.data + " -> ";
        str += node.right == null ? "." : node.right.data + "";
        System.out.println(str);
        display(node.left);
        display(node.right);
    }
    public static void main(String[] args) throws Exception {
        Scanner scn = new Scanner(System.in);
        int n = scn.nextInt();
        int arr[] = new int[n];
        for(int i=0;i<n;i++){
            arr[i]=scn.nextInt();
        }
        Arrays.sort(arr);
        Node root = construct(arr,0,arr.length-1);
        display(root);
    }
}
Solution 3: C++
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Node {
public:
    int data;
    Node* left;
    Node* right;
    Node(int data, Node* left, Node* right) : data(data), left(left), right(right) {}
};
Node* construct(int arr[], int lo, int hi) {
    if (lo > hi) return nullptr;
    int mid = hi - ((hi - lo) / 2);
    int data = arr[mid];
    Node* left = construct(arr, lo, mid - 1);
    Node* right = construct(arr, mid + 1, hi);
    Node* node = new Node(data, left, right);
    return node;
}
void display(Node* node) {
    if (node == nullptr) {
        return;
    }
    string str = "";
    str += (node->left == nullptr) ? "." : to_string(node->left->data);
    str += " <- " + to_string(node->data) + " -> ";
    str += (node->right == nullptr) ? "." : to_string(node->right->data);
    cout << str << endl;
    display(node->left);
    display(node->right);
}
int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  Â
    int n;
    cin >> n;
    int arr[n];
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    sort(arr, arr + n);
    Node* root = construct(arr, 0, n - 1);
    display(root);
    return 0;
}
Problem Statement 2
John works in a coin factory where each coin has an ID. He has an array 'nums' of size N. In the factory, coins are assigned to boxes based on the sum of the digits of their IDs. For example, if the ID of a coin is 321, the sum of its digits is 6 (since 3 + 2 + 1 = 6), so the coin will be placed in box 6.
John has been given a task to work with coins that have IDs in the range from the smallest number in 'nums', called the low-limit, to the largest number in 'nums', called the high-limit. For each number in this range (from low-limit to high-limit, inclusive), John needs to calculate the sum of the digits and place the coin in the corresponding box.
Help John determine which box contains the most coins and output the number of coins in that box.
Note: The factory has coins with IDs ranging from 0 to infinity, but John only needs to work with coins whose IDs lie between the low-limit and high-limit (inclusive).
Input Format
The first line contains an integer N, representing the number of elements in nums.
The second line contains n space-separated integers representing the elements of the array nums
Output Format
Print a single integer representing the maximum number of coins placed in any one box.
Constraints
1 <=N <=10^5
0 <= nums[i] <= 10^4
Solution 1: Python
# Enter your code here. Read input from STDIN. Print output to STDOUT
def count_balls_brute_force(arr):
   def countBalls1(lowLimit, highLimit):
       # Array to count the number of coins in each box
       cnt = [0] * 46
       for i in range(lowLimit, highLimit + 1):
           # Calculate the sum of digits using string conversion
           sum_of_digits = sum(int(digit) for digit in str(i))
           cnt[sum_of_digits] += 1
       return max(cnt)
   # Finding low and high limits
   low = min(arr)
   high = max(arr)
   return countBalls1(low, high)
# Read input
n = int(input())Â # Number of coins
arr = list(map(int, input().split()))Â # Array of coin numbers
# Output the result of the brute-force function
print(count_balls_brute_force(arr))
Solution 2: Java
import java.util.*;
public class Main {
   static int countBalls1(int lowLimit, int highLimit) {
       int[] cnt = new int[46];
       for (int i = lowLimit; i <= highLimit; ++i) {
           int sum = 0, n = i;
           while (n > 0) {
               sum += n % 10;
               n /= 10;
           }
           ++cnt[sum];
       }
       return Arrays.stream(cnt).max().getAsInt();
   }
   static int countBalls(List<Integer> arr) {
       Collections.sort(arr);
       int low = arr.get(0);
       int high = arr.get(arr.size() - 1);
       return countBalls1(low, high);
   }
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       int n = sc.nextInt();
       List<Integer> arr = new ArrayList<>();
       for (int i = 0; i < n; i++) {
           arr.add(sc.nextInt());
       }
       System.out.println(countBalls(arr));
   }
}
Solution 3: C++
#include<bits/stdc++.h>
using namespace std;
#define mod 1e9 + 7
typedef long long ll;
int countBalls1(int lowLimit, int highLimit) {
   // creating 46 sized count array
   int cnt[46] = {};
   // looping from lowLimit to highLimit
   for (auto i = lowLimit; i <= highLimit; ++i) {
       // sum variable for calculating the sum
       int sum = 0, n = i;
       // summing up the digits
       while(n) {
           sum += n % 10;
           n /= 10;
       }
       // incrementing the cnt[sum]
       ++cnt[sum];
   }
   // returning the max element from cnt vector
   return *max_element(begin(cnt), end(cnt));
}
int countBalls(vector<int>& arr){
   // sorting the arr vector
   sort(arr.begin(),arr.end());
   // finding low and high
   int low=arr[0],high=arr[arr.size()-1];
   // returning answer
   return countBalls1(low,high);
}
int main(){
   int n;
   cin>>n;
   vector<int>arr(n);
   for(int i=0;i<arr.size();i++){
       cin>>arr[i];
   }
   cout<<countBalls(arr)<<endl;
   return 0;
}
Problem Statement 3
Tom and Jerry are very naughty they always fight each other even for little things. This time they started fighting over a small cookie. The situation is such that there is a stream of numbers on a number line where there is a cookie present at the kth largest element in the array. Since Tom always gets the cookie from the master. Can you help jerry in getting the cookie as fast as possible?
Note: The kth largest element should be considered with repetition.
Input Format
The first line contains an integer that denotes the number of elements in the stream.
The second line contains K whose large value has the cookie.
The third line contains the stream of numbers
Output Format
The output contains a single integer which denotes the number at which cookie is there
Constraints
1 <= n <= 10^5
.-10^4 <= k, arr[i] <= 10^4
Testcase Input
30
5
10 10 1 0 1 1 1 9 10 7 2 6 8 7 7 1 5 1 4 5 6 4 6 5 7 8 2 7 9 2
Testcase Output
9
Solution 1: Java
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int k = scanner.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = scanner.nextInt();
        }
        System.out.println(findKthLargest(arr, k));
    }
    public static int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        for (int num : nums) {
            minHeap.offer(num);
            if (minHeap.size() > k) {
                minHeap.poll();
            }
        }
        return minHeap.peek();
    }
}
Solution 2: Python
import heapq
def num_largest(stream, K):
    min_heap = []
    for num in stream:
        if len(min_heap) < K:
            heapq.heappush(min_heap, num)
        else:
            if num > min_heap[0]:
                heapq.heapreplace(min_heap, num)
    if len(min_heap) == K:
        return min_heap[0]
    else:
        return None Â
def get_stream_from_user():
    while True:
        try:
            num_elements = int(input())
            break
        except ValueError:
            print("Please enter a valid number.")
    while True:
        try:
            K = int(input().strip()) # Read K
            break
        except ValueError:
            print("Please enter a valid number for K.")
    while True:
        try:
            user_input = input().strip()
            stream = list(map(int, user_input.split()))
            if len(stream) != num_elements:
                raise ValueError("Number of elements entered does not match the specified count.")
            break
        except ValueError as e:
            print(e)
    return stream, K
# Example usage:
 # Ask user for the value of K
stream, K = get_stream_from_user()
fifth_largest = num_largest(stream, K)
if fifth_largest is None:
    print("There are not enough unique numbers in the stream to find the K-th largest.")
else:
    print(fifth_largest)
Solution 3: C++
#include <cmath>
#include <cstdio>
#include <vector>
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */Â
     int n,k;
     cin>>n>>k;
     vector<int>a(n);
     for(int i=0;i<n;i++){
       cin>>a[i];
     }
     priority_queue<int>pq;
     for(int i=0;i<n;i++){
       pq.push(a[i]);
     }
     k--;
     while(k--){
       pq.pop();
     }
     cout<<pq.top()<<endl;
    return 0;
}
Problem Statement 4
You are given two sorted arrays, a1 and a2, of size m and n, respectively. Now we combine the values of these two arrays to make a mega array. The resulting mega array is also sorted in nature.
Your task is to find the median of this mega array.
Input Format
Each Input has three lines
The first line contains 2 values m and n respectively.
The second line contains m numbers that signify nums1.
The third line contains n numbers that signify nums2.
Output Format
Return a Double data type number, which is the median of two arrays.
Constraints
nums1.length == m
nums2.length == n
0 <= m <= 10^6
0 <= n <= 10^6
Solution 1: Python
def findMiddleEarth(a1, a2):
    n1, n2 = len(a1), len(a2)
    # We want to perform binary search on the smaller array
    if n2 < n1:
        return findMiddleEarth(a2, a1)
    low, high = 0, n1
    while low <= high:
        cut1 = (low + high) // 2
        # +1 because, if it's even suppose n1 = 4, n2 = 6, then cut2 will be 5
        # If it's odd suppose n1 = 3, n2 = 4, then cut2 will be 4 because we need +1 of mid
        cut2 = ((n1 + n2 + 1) // 2) - cut1
        left1 = float('-inf') if cut1 == 0 else a1[cut1 - 1]
        left2 = float('-inf') if cut2 == 0 else a2[cut2 - 1]
        right1 = float('inf') if cut1 == n1 else a1[cut1]
        right2 = float('inf') if cut2 == n2 else a2[cut2]
        if left1 <= right2 and left2 <= right1:
            if (n1 + n2) % 2 == 0:
                return (max(left1, left2) + min(right1, right2)) / 2.0
            else:
                return max(left1, left2)
        elif left1 > right2:
            high = cut1 - 1
        else:
            low = cut1 + 1
    return 0.0
def solution():
    m, n = map(int, input().split())
    a1 = list(map(int, input().split()))
    a2 = list(map(int, input().split()))
    print(findMiddleEarth(a1, a2))
if __name__ == "__main__":
    solution()
Solution 2: Java
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
class Main {
    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int n = sc.nextInt();
        int[] a1 = new int[m];
        for (int i = 0; i < m; i++) {
            a1[i] = sc.nextInt();
        }
        int[] a2 = new int[n];
        for (int i = 0; i < n; i++) {
            a2[i] = sc.nextInt();
        }
        // Call the optimized function to find the median
        double result = findMedianSortedArrays(a1, a2);
        if(result==(int)result){
            System.out.println((int)result);
        }else{
        System.out.println(result);
        }
    }
    public static double findMedianSortedArrays(int[] a1, int[] a2) {
        // Ensure that a1 is the smaller array
        if (a1.length > a2.length) {
            return findMedianSortedArrays(a2, a1);
        }
        int m = a1.length;
        int n = a2.length;
        int low = 0, high = m;
        while (low <= high) {
            int partitionA1 = (low + high) / 2;
            int partitionA2 = (m + n + 1) / 2 - partitionA1;
            int maxLeftA1 = (partitionA1 == 0) ? Integer.MIN_VALUE : a1[partitionA1 - 1];
            int minRightA1 = (partitionA1 == m) ? Integer.MAX_VALUE : a1[partitionA1];
            int maxLeftA2 = (partitionA2 == 0) ? Integer.MIN_VALUE : a2[partitionA2 - 1];
            int minRightA2 = (partitionA2 == n) ? Integer.MAX_VALUE : a2[partitionA2];
            if (maxLeftA1 <= minRightA2 && maxLeftA2 <= minRightA1) {
                // Found the correct partition
                if ((m + n) % 2 == 0) {
                    return (Math.max(maxLeftA1, maxLeftA2) + Math.min(minRightA1, minRightA2)) / 2.0;
                } else {
                    return Math.max(maxLeftA1, maxLeftA2);
                }
            } else if (maxLeftA1 > minRightA2) {
                // Move towards the left in a1
                high = partitionA1 - 1;
            } else {
                // Move towards the right in a1
                low = partitionA1 + 1;
            }
        }
        throw new IllegalArgumentException("Input arrays are not sorted.");
    }
}
Solution 3: C++
#include <cmath>
#include <climits>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
double solve(vector<int>&arr1, vector<int>&arr2, int n1, int n2){
    int total = (n1+n2+1)/2;
    int n=n1+n2;
    if(n1>n2){
        return solve(arr2, arr1, n2, n1);
    }
    int low=0;
    int high=n1;
    while(low<=high){
        int mid1=(low+high)/2;
        int mid2=total-mid1;
        int l1 = mid1-1>=0?arr1[mid1-1]:INT_MIN;
        int r1 = mid1<n1?arr1[mid1]:INT_MAX;
        int l2 = mid2-1>=0?arr2[mid2-1]:INT_MIN;
        int r2 = mid2<n2?arr2[mid2]:INT_MAX;
        if(l1<=r2 && r1>=l2){
            if(n%2==0){
                return double(max(l1, l2)+min(r1, r2))/2;
            }
            return double(max(l1, l2));
        }
        else if(l1>r2){
            high=mid1-1;
        }
        else{
            low=mid1+1;
        }
    }
    return 0;
}
int main() {
    int n1;
    int n2;
    cin>>n1>>n2;
    vector<int>arr1;
    vector<int>arr2;Â
    for(int i=0; i<n1; i++){
        int u;
        cin>>u;
        arr1.push_back(u);
    } Â
    for(int j=0; j<n2; j++){
        int v;
        cin>>v;
        arr2.push_back(v);
    }
    cout<<solve(arr1, arr2, n1, n2);
    return 0;
}
Problem Statement 5
From your balcony, you can see N trees standing in a line numbered from 1 to N. The ith tree has height hi. Using your binoculars, you can only look at K trees at once in a single frame. A frame is defined by the index of the leftmost tree in it and contains exactly K trees. Starting from frame 1 (the leftmost frame), you move your binoculars towards the right until you reach frame N-K+1 (the rightmost possible frame). You want to find the height of the highest tree in each frame that is captured by your binoculars
Input Format
The first line of the input contains two integers N and K denoting the total number of trees and number of trees in a frame.
The second line contains N integers a1, a2, .., aN where ai represents the height of each tree.
Output Format
Print N-K+1 space-separated integers the height of the highest tree in each frame.
Constraints
1 <= N <= 10^9
1 <= K <= N
1 <= ai <= 10^9
Testcase Input
8 3
1 3 1 2 5 3 6 7
Testcase Output
3 3 5 5 6 7
Solution 1: C++
#include <bits/stdc++.h>
using namespace std;
int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  Â
    deque<int> dq;
    int n,k;
    cin>>n>>k;
    int a[n];
    for(int i=0;i<n;i++){
        cin>>a[i];
        if(dq.empty() || a[dq.front()]<=a[i]){
            dq.push_front(i);
        }else{
            while(!dq.empty() && (a[i]>=a[dq.back()] || dq.back()<=i-k)){
                dq.pop_back();
            }
            dq.push_back(i);
        }
                while(!dq.empty() && dq.front()<=i-k)dq.pop_front();
        if(i>=k-1){
            cout<<a[dq.front()]<<" ";
        }              Â
    }
    return 0;
}
Solution 2: Python
from collections import deque
def sliding_window_maximum(N, K, heights):
    if K > N:
        return
    max_in_windows = []
    deq = deque()
    for i in range(N):
        if deq and deq[0] < i - K + 1:
            deq.popleft()
        while deq and heights[deq[-1]] <= heights[i]:
            deq.pop()
        deq.append(i)
        if i >= K - 1:
            max_in_windows.append(heights[deq[0]])
    return max_in_windows
if __name__ == "__main__":
    import sys
    input = sys.stdin.read
    data = input().split()
    N = int(data[0])
    K = int(data[1])
    heights = list(map(int, data[2:]))
    result = sliding_window_maximum(N, K, heights)
    print(" ".join(map(str, result)))
Solution 3: Java
import java.util.*;
class Main {
    // Function declaration
    public static List<Integer> getMaxHeightsInFrames(int n, int k, List<Integer> heights) {
        // User will write the logic here
        List<Integer> res= new ArrayList <>();
        int r=0,max;
        while(r< (n-k+1))
        {
            max=Integer.MIN_VALUE;
            for(int i=r;i<r+k;i++)
            {
                max=Math.max(max,heights.get(i));
            }
            res.add(max);
            r++;
        }
        return res;
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Read inputs
        int n = scanner.nextInt();
        int k = scanner.nextInt();
        List<Integer> heights = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            heights.add(scanner.nextInt());
        }
        // Call the function
        List<Integer> result = getMaxHeightsInFrames(n, k, heights);
        // Print the result
        for (int height : result) {
            System.out.print(height + " ");
        }
    }
}
Conclusion
HCL coding questions and interview questions are structured to assess technical expertise, problem-solving efficiency, and understanding of data structures and algorithms. Candidates can benefit from a structured preparation approach that focuses on common coding challenges, algorithm design, and optimization techniques.
Disclaimer: While we have gathered as much information from HCL's official website as possible, we have also included sources gathered from available online sources. Therefore, readers are advised to check and stay updated with the official website.
Frequently Asked Questions (FAQs)
1. What programming languages should I focus on for HCL coding questions?
HCL generally allows candidates to code in languages like Java, Python, and C++, as these are versatile and widely used in their technical assessments. It’s beneficial to be proficient in at least one of these, with a strong knowledge of data structures and algorithms.
2. What type of coding questions are typically asked in HCL’s online test?
The online coding test usually includes questions on data structures (like arrays, strings, and linked lists), algorithms (sorting, searching), and sometimes dynamic programming. Additionally, there may be questions on recursion, string manipulation, and basic database queries.
3. Are HCL coding questions timed, and how should I manage my time?
Yes, HCL coding assessments are timed, typically allowing candidates around 45-60 minutes to solve 2-3 coding problems. Time management is crucial, so it’s best to start with the easier problem, ensure accuracy, and allocate more time to complex questions while focusing on writing optimized code.
4. How can I prepare effectively for HCL coding questions?
Practice and focus on data structures, problem-solving, and algorithm-based questions. Reviewing HCL’s previous year coding questions and improving efficiency in coding will help in preparation.
5. What is the difficulty level of HCL coding questions, and is optimization important?
The difficulty level ranges from moderate to high, with some questions specifically testing algorithm optimization skills. Optimization is key, as it demonstrates the ability to solve problems within time and space constraints—especially for roles requiring high technical proficiency.
Suggested reads:
-
Deloitte Coding Questions: Top 5 Coding Questions for Freshers
-
TCS Digital Recruitment Process: Latest Updates & Tips for Freshers
-
HCL Logical Reasoning Questions and Answers: Top 5 Sample MCQs
-
HCL Aptitude Test: Top 5 Questions and Answers for Freshers (MCQs)
-
TCS Digital Aptitude Questions and Answers: Top 5 Sample MCQs
Instinctively, I fall for nature, music, humour, reading, writing, listening, travelling, observing, learning, unlearning, friendship, exercise, etc., all these from the cradle to the grave- that's ME! It's my irrefutable belief in the uniqueness of all. I'll vehemently defend your right to be your best while I expect the same from you!
Login to continue reading
And access exclusive content, personalized recommendations, and career-boosting opportunities.
Blogs you need to hog!

55+ Data Structure Interview Questions For 2025 (Detailed Answers)

How To Negotiate Salary With HR: Tips And Insider Advice

Best 80+ TCS NQT Most Commonly Asked Interview Questions for 2025

Comments
Add comment