HCLIT Codes Zone

HCL Previous Coding Questions

Table of Contents

πŸ”₯ HCL Previous Coding Questions with Java & Python Solutions

Welcome to this specially curated post featuring HCL Previous Coding Questions asked in real placement drives and technical assessments.
Each problem includes:

βœ… A clear and structured problem statement
βœ… Java and Python solutions
βœ… Example input and output
βœ… Concise explanation to understand the logic

Whether you’re preparing for HCL interviews or just want to sharpen your coding skills β€” this guide will help you practice and master the most frequently asked problems.
Let’s dive in! πŸš€


βœ… Problem 1: Sum of Digits in a String

πŸ“ Problem Statement

You are given a string containing a mix of alphabets, digits, and possibly special characters. Your task is to extract all digits and calculate their total sum. This question tests your ability to handle string traversal and conditional logic efficiently.

πŸ”’ Input

  • A string with a mix of characters (letters, digits, symbols).
  • Length ≀ 100 characters.

🧾 Output

  • An integer representing the sum of all numeric digits in the input.

βœ… Example

Input:
abc123def45
Output:
15

πŸ”£Code

def sum_of_digits(s):
    total = 0
    for ch in s:
        if ch.isdigit():
            total += int(ch)
    return total

# Example
input_str = "abc123def45"
print(sum_of_digits(input_str))
public class Main {
    public static void main(String[] args) {
        String input = "abc123def45";
        int sum = 0;
        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);
            if (Character.isDigit(ch)) {
                sum += Character.getNumericValue(ch);
            }
        }
        System.out.println(sum);
    }
}

πŸ” Explanation

The program loops through each character in the string, checks if it’s a digit, and adds its value to the total sum.

βœ… Problem 2: Reverse Each Word in a Sentence

πŸ“ Problem Statement

Write a program to reverse every word in a given sentence, keeping the word order the same. This problem tests string splitting and word-level manipulation.

πŸ”’ Input

  • A single line sentence with multiple words.

🧾 Output

  • The sentence with each word reversed individually.

βœ… Example

Input:
hello world
Output:
olleh dlrow

πŸ”£Code

def reverse_words(sentence):
    words = sentence.split()
    result = [word[::-1] for word in words]
    return ' '.join(result)

print(reverse_words("hello world"))
public class Main {
    public static void main(String[] args) {
        String sentence = "hello world";
        String[] words = sentence.split(" ");
        StringBuilder result = new StringBuilder();
        for (String word : words) {
            result.append(new StringBuilder(word).reverse().toString()).append(" ");
        }
        System.out.println(result.toString().trim());
    }
}

πŸ” Explanation

Split the sentence into words, reverse each word, and join them back with spaces.

βœ… Problem 3: Count Vowels in a String

πŸ“ Problem Statement

Write a program that counts the number of vowels (a, e, i, o, u) in a string, ignoring case. This checks basic character handling.

πŸ”’ Input

  • A lowercase or mixed-case string.

🧾 Output

  • Total number of vowels found.

βœ… Example

Input:
Education
Output:
5

πŸ”£Code

def count_vowels(s):
    vowels = 'aeiouAEIOU'
    count = 0
    for ch in s:
        if ch in vowels:
            count += 1
    return count

print(count_vowels("Education"))
public class Main {
    public static void main(String[] args) {
        String input = "Education";
        int count = 0;
        for (char ch : input.toCharArray()) {
            if ("aeiouAEIOU".indexOf(ch) != -1) {
                count++;
            }
        }
        System.out.println(count);
    }
}

πŸ” Explanation

Each character is checked against a list of vowels. If it matches, the count is increased.

βœ… Problem 4: Check Palindrome String

πŸ“ Problem Statement

Determine whether the given string is a palindrome (reads the same forward and backward). Ignore case and assume no spaces or symbols.

πŸ”’ Input

  • A single word or string.

🧾 Output

  • True if it is a palindrome, otherwise False.

βœ… Example

Input:
madam
Output:
True

πŸ”£Code

def is_palindrome(s):
    return s.lower() == s[::-1].lower()

print(is_palindrome("madam"))
public class Main {
    public static void main(String[] args) {
        String str = "madam";
        String reversed = new StringBuilder(str).reverse().toString();
        System.out.println(str.equalsIgnoreCase(reversed));
    }
}

πŸ” Explanation

The string is reversed and compared to the original (ignoring case).

βœ… Problem 5: Find Maximum Number in List

πŸ“ Problem Statement

Given a list of integers, find the largest number using a simple loop. This is useful to test basic iteration and condition logic.

πŸ”’ Input

  • A list of integers separated by spaces.

🧾 Output

  • The maximum number in the list.

βœ… Example

Input:
10 20 45 6 78
Output:
78

πŸ”£Code

def find_max(numbers):
    max_val = numbers[0]
    for num in numbers:
        if num > max_val:
            max_val = num
    return max_val

print(find_max([10, 20, 45, 6, 78]))
public class Main {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 45, 6, 78};
        int max = numbers[0];
        for (int num : numbers) {
            if (num > max) {
                max = num;
            }
        }
        System.out.println(max);
    }
}

πŸ” Explanation

Compare each number in the list and store the highest seen so far in a variable.

βœ… Problem 6: Count Words in a Sentence

πŸ“ Problem Statement

Write a program to count the number of words in a sentence. Words are separated by spaces. This tests basic string manipulation and understanding of delimiters.

πŸ”’ Input

  • A sentence containing words separated by spaces.

🧾 Output

  • An integer representing the word count.

βœ… Example

Input:
HCL is hiring software engineers
Output:
5

πŸ”£Code

def count_words(sentence):
    words = sentence.split()
    return len(words)

print(count_words("HCL is hiring software engineers"))
public class Main {
    public static void main(String[] args) {
        String sentence = "HCL is hiring software engineers";
        String[] words = sentence.split(" ");
        System.out.println(words.length);
    }
}

πŸ” Explanation

Split the sentence into words using spaces and return the length of the resulting array/list.

βœ… Problem 7: Print Fibonacci Series up to N Terms

πŸ“ Problem Statement

Write a program to print the first N terms of the Fibonacci sequence. This helps evaluate your loop control and series logic.

πŸ”’ Input

  • An integer N representing the number of terms.

🧾 Output

  • N Fibonacci numbers separated by spaces.

βœ… Example

Input:
5
Output:
0 1 1 2 3

πŸ”£Code

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        print(a, end=" ")
        a, b = b, a + b

fibonacci(5)
public class Main {
    public static void main(String[] args) {
        int n = 5, a = 0, b = 1;
        for (int i = 0; i < n; i++) {
            System.out.print(a + " ");
            int temp = a + b;
            a = b;
            b = temp;
        }
    }
}

πŸ” Explanation

Fibonacci starts with 0 and 1, and each number is the sum of the previous two. Loop N times to print the sequence.

βœ… Problem 8: Find Factorial of a Number

πŸ“ Problem Statement

Write a program to find the factorial of a non-negative integer N using iteration. This assesses your understanding of loops and multiplication.

πŸ”’ Input

  • A non-negative integer N.

🧾 Output

  • Factorial of the number.

βœ… Example

Input:
5
Output:
120

πŸ”£Code

def factorial(n):
    result = 1
    for i in range(2, n+1):
        result *= i
    return result

print(factorial(5))
public class Main {
    public static void main(String[] args) {
        int n = 5, fact = 1;
        for (int i = 2; i <= n; i++) {
            fact *= i;
        }
        System.out.println(fact);
    }
}

πŸ” Explanation

Multiply all numbers from 2 to N to get the factorial. Loop handles the multiplication iteratively.

βœ… Problem 9: Print Even Numbers from 1 to N

πŸ“ Problem Statement

Write a program that prints all even numbers between 1 and N. This helps check your grasp of modulus operations and loops.

πŸ”’ Input

  • An integer N.

🧾 Output

  • All even numbers from 1 to N.

βœ… Example

Input:
10
Output:
2 4 6 8 10

πŸ”£Code

def print_even(n):
    for i in range(2, n+1, 2):
        print(i, end=" ")

print_even(10)
public class Main {
    public static void main(String[] args) {
        int n = 10;
        for (int i = 2; i <= n; i += 2) {
            System.out.print(i + " ");
        }
    }
}

πŸ” Explanation

Start from 2 and increment by 2 to directly get even numbers, avoiding unnecessary checks.

βœ… Problem 10: Reverse a Number

πŸ“ Problem Statement

Given a number, write a program to reverse its digits. This problem tests your ability to use modulus and integer division.

πŸ”’ Input

  • A positive integer.

🧾 Output

  • Reversed number.

βœ… Example

Input:
1234
Output:
4321

πŸ”£Code

def reverse_number(n):
    rev = 0
    while n > 0:
        rev = rev * 10 + n % 10
        n //= 10
    return rev

print(reverse_number(1234))
public class Main {
    public static void main(String[] args) {
        int n = 1234, rev = 0;
        while (n > 0) {
            rev = rev * 10 + n % 10;
            n /= 10;
        }
        System.out.println(rev);
    }
}

πŸ” Explanation

Use modulus to get last digit and build the reverse number by shifting existing digits left (multiply by 10).

βœ… Problem 11: Find the Maximum of Three Numbers

πŸ“ Problem Statement

Write a program to find the largest of three numbers. This tests your understanding of conditional statements and comparison operators.

πŸ”’ Input

  • Three integers a, b, and c

🧾 Output

  • The largest of the three numbers

βœ… Example

Input:
5 12 9
Output:
12

πŸ”£Code

def find_max(a, b, c):
    return max(a, b, c)

print(find_max(5, 12, 9))
public class Main {
    public static void main(String[] args) {
        int a = 5, b = 12, c = 9;
        int max = Math.max(a, Math.max(b, c));
        System.out.println(max);
    }
}

πŸ” Explanation

Use built-in methods or nested comparisons to find the greatest among three values.

βœ… Problem 12: Check Whether a Number is Prime

πŸ“ Problem Statement

Write a program to check whether a number is a prime or not. This helps evaluate loop, condition checking, and divisor logic.

πŸ”’ Input

  • An integer n

🧾 Output

  • “Prime” if the number is prime, else “Not Prime”

βœ… Example

Input:
7
Output:
Prime

πŸ”£Code

def is_prime(n):
    if n < 2:
        return "Not Prime"
    for i in range(2, int(n**0.5)+1):
        if n % i == 0:
            return "Not Prime"
    return "Prime"

print(is_prime(7))
public class Main {
    public static void main(String[] args) {
        int n = 7, flag = 0;
        if (n < 2) flag = 1;
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                flag = 1;
                break;
            }
        }
        System.out.println(flag == 0 ? "Prime" : "Not Prime");
    }
}

πŸ” Explanation

Check divisibility from 2 to √n. If divisible by any, it’s not prime.

βœ… Problem 13: Sum of Digits of a Number

πŸ“ Problem Statement

Given an integer, write a program to calculate the sum of its digits. This is a basic math problem involving modulus and loops.

πŸ”’ Input

  • An integer n

🧾 Output

  • Sum of digits

βœ… Example

Input:
123
Output:
6

πŸ”£Code

def sum_of_digits(n):
    total = 0
    while n > 0:
        total += n % 10
        n //= 10
    return total

print(sum_of_digits(123))
public class Main {
    public static void main(String[] args) {
        int n = 123, sum = 0;
        while (n > 0) {
            sum += n % 10;
            n /= 10;
        }
        System.out.println(sum);
    }
}

πŸ” Explanation

Use modulus to extract digits and add them in a loop.

βœ… Problem 14: Find GCD of Two Numbers

πŸ“ Problem Statement

Write a program to compute the greatest common divisor (GCD) of two numbers using the Euclidean algorithm.

πŸ”’ Input

  • Two integers a and b

🧾 Output

  • The GCD of the two numbers

βœ… Example

Input:
24 36
Output:
12

πŸ”£Code

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

print(gcd(24, 36))
public class Main {
    public static void main(String[] args) {
        int a = 24, b = 36;
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        System.out.println(a);
    }
}

πŸ” Explanation

Use the Euclidean algorithm: GCD(a, b) = GCD(b, a % b) until b becomes 0.

βœ… Problem 15: Find the Second Largest Number

πŸ“ Problem Statement

Given an array of integers, write a program to find the second largest distinct number. Make sure to ignore duplicate highest values.

πŸ”’ Input

  • An array of integers

🧾 Output

  • An integer representing the second highest unique number.

βœ… Example

Input:
[10, 20, 4, 45, 99, 99]
Output:
45

πŸ”£Code

def second_largest(nums):
    unique_nums = list(set(nums))
    unique_nums.sort()
    return unique_nums[-2]

print(second_largest([10, 20, 4, 45, 99, 99]))
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Integer[] arr = {10, 20, 4, 45, 99, 99};
        Set<Integer> set = new HashSet<>(Arrays.asList(arr));
        List<Integer> list = new ArrayList<>(set);
        Collections.sort(list);
        System.out.println(list.get(list.size() - 2));
    }
}

πŸ” Explanation

To avoid counting duplicates, we convert the list to a set. Then we sort the set and return the second last item. Sorting is key to ensure proper comparison.

βœ… Problem 16: Toggle Case of String

πŸ“ Problem Statement

Write a program to toggle each character’s case from a string. Uppercase becomes lowercase, and lowercase becomes uppercase.

πŸ”’ Input

  • A string

🧾 Output

  • A toggled version of input string

βœ… Example

Input:
"HeLLo"
Output:
"hEllO"

πŸ”£Code

def toggle_case(s):
    return s.swapcase()

print(toggle_case("HeLLo"))
public class Main {
    public static void main(String[] args) {
        String input = "HeLLo";
        StringBuilder toggled = new StringBuilder();

        for (char c : input.toCharArray()) {
            if (Character.isUpperCase(c))
                toggled.append(Character.toLowerCase(c));
            else
                toggled.append(Character.toUpperCase(c));
        }

        System.out.println(toggled.toString());
    }
}

πŸ” Explanation

Use built-in swapcase() in Python. In Java, loop through each character and flip the case using Character.isUpperCase() and conversion methods.

βœ… Problem 17: Sum of All Even Numbers from 1 to N

πŸ“ Problem Statement

Write a program that takes an integer N and returns the sum of all even numbers from 1 to N. This helps test for loops and conditional logic.

πŸ”’ Input

  • An integer(N)

🧾 Output

  • Sum of even numbers from 1 to N.

βœ… Example

Input:
10
Output:
30 (2+4+6+8+10)

πŸ”£Code

def sum_even(n):
    total = 0
    for i in range(2, n+1, 2):
        total += i
    return total

print(sum_even(10))
public class Main {
    public static void main(String[] args) {
        int n = 10, sum = 0;
        for (int i = 2; i <= n; i += 2) {
            sum += i;
        }
        System.out.println(sum);
    }
}

πŸ” Explanation

Use a loop that starts from 2 and increments by 2. This avoids checking each number with if condition and is more efficient.

βœ… Problem 18: Remove Duplicates from List

πŸ“ Problem Statement

Remove all duplicate elements from an input list while preserving the order of the first occurrence.

πŸ”’ Input

  • A list of Integers

🧾 Output

  • A list with unique elements in the given list

βœ… Example

Input:
[1, 2, 2, 3, 4, 3, 5]
Output:
[1, 2, 3, 4, 5]

πŸ”£Code

def remove_duplicates(lst):
    result = []
    seen = set()
    for num in lst:
        if num not in seen:
            seen.add(num)
            result.append(num)
    return result

print(remove_duplicates([1, 2, 2, 3, 4, 3, 5]))
import java.util.*;

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 2, 3, 4, 3, 5};
        Set<Integer> seen = new HashSet<>();
        List<Integer> result = new ArrayList<>();

        for (int num : arr) {
            if (!seen.contains(num)) {
                seen.add(num);
                result.add(num);
            }
        }

        System.out.println(result);
    }
}

πŸ” Explanation

Use a set to track seen elements and a list to maintain order. This ensures duplicates are removed but original sequence is preserved.

βœ… Problem 19: Print Star Pyramid Pattern

πŸ“ Problem Statement

Write a program that prints a star pyramid with N rows. This improves nested loop and pattern printing skills.

πŸ”’ Input

  • An integer N (number of rows)

🧾 Output

  • Pyramid pattern

βœ… Example

Input:
3
Output:

  *
 ***
*****

πŸ”£Code

def print_pyramid(n):
    for i in range(n):
        print(' ' * (n - i - 1) + '*' * (2 * i + 1))

print_pyramid(3)
public class Main {
    public static void main(String[] args) {
        int n = 3;
        for (int i = 0; i < n; i++) {
            System.out.print(" ".repeat(n - i - 1));
            System.out.println("*".repeat(2 * i + 1));
        }
    }
}

πŸ” Explanation

Each row has spaces followed by stars based on the current row index.

βœ… Problem 20: Replace All Spaces with Underscores

πŸ“ Problem Statement

Given a string, replace every space with an underscore _. This problem helps assess basic string manipulation.

πŸ”’ Input

  • A sentence like "HCL placement question"

🧾 Output

  • a sentence “HCL_placement_question”, by replacing spaces with underscore

βœ… Example

Input:
"HCL placement question"
Output:
"HCL_placement_question"

πŸ”£Code

def replace_spaces(s):
    return s.replace(" ", "_")

print(replace_spaces("HCL placement question"))
public class Main {
    public static void main(String[] args) {
        String input = "HCL placement question";
        String output = input.replace(" ", "_");
        System.out.println(output);
    }
}

πŸ” Explanation

String replace is a direct and efficient way to modify specific characters. Both languages provide this as a built-in function for convenience.

🚨 Revature Overview!

Curious about how Revature’s selection process works, the rounds involved, and other key details? Don’t miss this complete breakdown:
🌐 https://nextgenkodinghub.in/hcl-overview/

Wishing you the best of luck! πŸ’Όβœ¨


Thanks for visiting! Explore the categories below for more exciting and useful content.


Leave a Reply

Your email address will not be published. Required fields are marked *