HP Coding Questions and Answers

HP Coding Questions with Solutions

This page will help you to get HP Enterprise Coding Questions and Answers asked in the Recruitment Process of the company. Other than that you will find Insights on Online Assessments, Steps involved in the Recruitment Process, Eligibility Criteria, CTC Offered, Interview Rounds, and Job Profiles offered. 

HP Enterprise offers various roles for freshers, to get more specific details please go through this page.

junglee-games-coding-questions-and-answers-pdf

About HP Enterprise

HP Enterprise (Hewlett Packard Enterprise) is a global technology company that provides a wide range of products, solutions, and services for businesses and organizations. It was formed in 2015 as a result of the split of the Hewlett-Packard Company into two separate entities, with HP Enterprise focusing on enterprise-level products and services.

HP Enterprise serves a wide range of industries, including healthcare, finance, government, telecommunications, manufacturing, and more. The company focuses on delivering innovative solutions that help organizations transform their businesses, increase agility, and drive growth.

About HP Enterprise Recruitment Process

This Recruitment process consists of the following steps :

  1. Online Assessment [Aptitude, Verbal and Technical Based ]
  2. Technical Interview
  3. HR Interview

We have mentioned further details of the HP Enterprise Recruitment Process in the following Tabular Form

HP Enterprise Related Information
Position :
  • Software Engineer
  • Software Developer
Course :
  • B.Tech / M.Tech
  • Eligible Batch – 2023
Eligibility Criteria / Academic Qualification Required :
  • Minimum 60% or equivalent CGPA of 6 and above in 10th and 12th
  • Minimum 6.5 CGPA in Graduation / Post Graduation.
  • No Backlogs
Cost to Company (CTC)
  • Software Engineer Role : 8 – 10 LPA
  • Software Developer Role : 9 – 12 LPA
Selection Process :
  1. Online Assessment
  2. Technical Interview
  3. HR Interview

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Sample HP Enterprise Coding Questions With Solutions

Question 1: Detecting loop in a linked list

Problem Statement –  You are given a singly linked list, where each node contains a value and a pointer to the next node in the list. Your task is to determine if the linked list contains a cycle or not.

A cycle in a linked list occurs when there is a node in the list whose next pointer points to a previously visited node, creating a loop.

You need to implement an efficient solution with a time complexity of O(n) and a space complexity of O(1), where n is the number of nodes in the linked list.

Function Description:

Complete the hasLoop function that takes the head of the linked list as input and returns true if a cycle exists, and false otherwise.

Constraints:

  • The number of the nodes in the list is in the range [1, 99].
  • -105 <= Node.val <= 105

Sample Cases

Sample Input :

list = [1, 2, 3, 4]

loop at 4 -> 1

Sample Output :
Loop Detected

Run
#include<bits/stdc++.h>
using namespace std;

class ListNode {
public:
    int value;
    ListNode* next;
};

void insertAtBeginning(ListNode** head, int newValue) {
    ListNode* newNode = new ListNode();
    newNode->value = newValue;
    newNode->next = (*head);
    (*head) = newNode;
}

int detectLoop(ListNode* list) {
    ListNode* slowPtr = list;
    ListNode* fastPtr = list;

    while (slowPtr && fastPtr && fastPtr->next) {
        slowPtr = slowPtr->next;
        fastPtr = fastPtr->next->next;
        if (slowPtr == fastPtr) {
            return 1;
        }
    }
    return 0;
}

int main() {
    ListNode* head = NULL;

    insertAtBeginning(&head, 1);
    insertAtBeginning(&head, 2);
    insertAtBeginning(&head, 3);
    insertAtBeginning(&head, 4);
    insertAtBeginning(&head, 5);
    
    head->next->next->next->next->next = head;
    if (detectLoop(head))
        cout << "Loop Found";
    else
        cout << "No Loop";
    return 0;
}
Run
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None


class LinkedList:
    def __init__(self):
        self.head = None

    def push(self, new_data):
        new_node = Node(new_data)
        new_node.next = self.head
        self.head = new_node

    def printList(self):
        temp = self.head
        while temp:
            print(temp.data)
            temp = temp.next

    def detectLoop(self):
        slow_ptr = self.head
        fast_ptr = self.head
        while slow_ptr and fast_ptr and fast_ptr.next:
            slow_ptr = slow_ptr.next
            fast_ptr = fast_ptr.next.next
            if slow_ptr == fast_ptr:
                return 1
        return 0


linklist = LinkedList()
linklist.push(1)
linklist.push(2)
linklist.push(3)
linklist.push(4)

linklist.head.next.next.next.next = linklist.head
if linklist.detectLoop():
    print("Loop Found")
else:
    print("No Loop")
Run
public class Main
{
    Node head; 

    class Node {
        int data;
        Node next;

        Node(int data) {
            this.data = data;
            this.next = null;
        }
    }

    void insert(int data) {
        Node newNode = new Node(data);

        if (head == null) {
            head = newNode;
        } else {
            Node current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
    }

    boolean hasCycle() {
        if (head == null || head.next == null) {
            return false;
        }

        Node slowPtr = head;
        Node fastPtr = head.next;

        while (fastPtr != null && fastPtr.next != null) {
            if (slowPtr == fastPtr) {
                return true;
            }
            slowPtr = slowPtr.next;
            fastPtr = fastPtr.next.next;
        }

        return false;
    }

    public static void main(String[] args) {
        Main linkedList = new Main();
        
        linkedList.insert(1);
        linkedList.insert(2);
        linkedList.insert(3);
        linkedList.insert(4);
        linkedList.insert(5);
        linkedList.head.next.next.next.next.next = linkedList.head;

        if (linkedList.hasCycle()) {
            System.out.println("Cycle Detected");
        } else {
            System.out.println("No Cycle Detected");
        }
    }
}

Question 2: Stepping Numbers

Problem Description :

Stepping Numbers are numbers in which the adjacent digits differ by 1. For example, 123, 545, and 98 are stepping numbers, while 321, 444, and 75 are not. The task is to find all stepping numbers in a given range [n, m].

  • For example
    • Range: [100, 500]
    • Stepping Numbers: 101, 121, 123, 210, 212, 232, 234, 321, 323, 343, 345
    • Explanation: The stepping numbers between 100 and 500 are 101, 121, 123, 210, 212, 232, 234, 321, 323, 343, and 345. These numbers have adjacent digits that differ by 1.

Write code to find out all the stepping numbers in the given range.

Input Format: First line contains two numbers N,M

Output Format: Print all the stepping numbers present in the range.

Constraints: 0 <= N < M <= 1,000,000,000

Run
#include <stdio.h>

void displaySteppingNumbers(int n, int m) {
    int queue[10000];
    int front = 0, rear = -1;

    for (int i = 1; i <= 9; i++) {
        queue[++rear] = i;
    }

    while (front <= rear) { int stepNum = queue[front++]; if (stepNum >= n && stepNum <= m) { printf("%d ", stepNum); } if (stepNum == 0 || stepNum > m) {
            continue;
        }

        int lastDigit = stepNum % 10;

        int stepNumA = stepNum * 10 + (lastDigit - 1);
        int stepNumB = stepNum * 10 + (lastDigit + 1);

        if (lastDigit == 0) {
            queue[++rear] = stepNumB;
        } else if (lastDigit == 9) {
            queue[++rear] = stepNumA;
        } else {
            queue[++rear] = stepNumA;
            queue[++rear] = stepNumB;
        }
    }
}

int main() {
    int n, m;
    printf("Enter the range [n, m]: ");
    scanf("%d %d", &n, &m);

    printf("Stepping Numbers between %d and %d: ", n, m);
    displaySteppingNumbers(n, m);

    return 0;
}
Run
#include <iostream>
#include <queue>
using namespace std;

void displaySteppingNumbers(int n, int m) {
    queue<int> q; 
    for (int i = 1; i <= 9; i++) {
        q.push(i);
    }
    while (!q.empty()) {
        int stepNum = q.front();
        q.pop();
        if (stepNum >= n && stepNum <= m) {
            cout << stepNum << " ";
        }
        if (stepNum == 0 || stepNum > m) {
            continue;
        }
        int lastDigit = stepNum % 10;
        int stepNumA = stepNum * 10 + (lastDigit - 1);
        int stepNumB = stepNum * 10 + (lastDigit + 1);
        if (lastDigit == 0) {
            q.push(stepNumB);
        } else if (lastDigit == 9) {
            q.push(stepNumA);
        } else {
            q.push(stepNumA);
            q.push(stepNumB);
        }
    }
}

int main() {
    int n, m;
    cout << "Enter the range [n, m]: ";
    cin >> n >> m;
    cout << "Stepping Numbers between " << n << " and " << m << ": ";
    displaySteppingNumbers(n, m);
    return 0;
}

Run
import java.util.LinkedList;
import java.util.Queue;

public class Main {
    public static void displaySteppingNumbers(int n, int m) {
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 1; i <= 9; i++) {
            queue.add(i);
        }
        while (!queue.isEmpty()) {
            int stepNum = queue.poll();
            if (stepNum >= n && stepNum <= m) {
                System.out.print(stepNum + " ");
            }
            if (stepNum == 0 || stepNum > m) {
                continue;
            }
            int lastDigit = stepNum % 10;
            int stepNumA = stepNum * 10 + (lastDigit - 1);
            int stepNumB = stepNum * 10 + (lastDigit + 1);
            if (lastDigit == 0) {
                queue.add(stepNumB);
            } else if (lastDigit == 9) {
                queue.add(stepNumA);
            } else {
                queue.add(stepNumA);
                queue.add(stepNumB);
            }
        }
    }

    public static void main(String[] args) {
        int n = 0, m = 100;
        System.out.print("Stepping Numbers between " + n + " and " + m + ": ");
        displaySteppingNumbers(n, m);
    }
}

Run
def displaySteppingNumbers(n, m):
    queue = []
    for i in range(1, 10):
        queue.append(i)
    while queue:
        stepNum = queue.pop(0)
        if stepNum >= n and stepNum <= m:
            print(stepNum, end=' ')
        if stepNum == 0 or stepNum > m:
            continue
        lastDigit = stepNum % 10
        stepNumA = stepNum * 10 + (lastDigit - 1)
        stepNumB = stepNum * 10 + (lastDigit + 1)
        if lastDigit == 0:
            queue.append(stepNumB)
        elif lastDigit == 9:
            queue.append(stepNumA)
        else:
            queue.append(stepNumA)
            queue.append(stepNumB)
n = 0
m = 100
print("Stepping Numbers between", n, "and", m, ": ", end='')
displaySteppingNumbers(n, m)

Question 3: Remove all characters in a given string that are not lowercase or numerical

The task is to remove all characters in a given string that are not lowercase letters or numerical digits. The purpose is to clean the string and only keep the lowercase letters (a-z) and numerical digits (0-9), discarding any other characters such as whitespace, punctuation marks, or uppercase letters.

  • For example
    • Input: “Hello!123$”
    • Output: “ello123”
    • Explanation: The input string contains uppercase letters, an exclamation mark, and a dollar sign. After removing all characters that are not lowercase or numerical, only the lowercase letters “e”, “l”, “l”, “o”, and the numerical digits “1”, “2”, “3” remain.

Write the code to remove all characters in a given string that are not lowercase or numerical.

Input Format: First line contains two numbers N,M

Output Format: Print all the stepping numbers present in the range.

Constraints: 0 <= N < M <= 1,000,000,000

Run
#include <stdio.h>
#include <ctype.h>
void removeNonAlphanumeric(char *str) {
    char *readPtr = str;
    char *writePtr = str;
    while (*readPtr) {
        if (islower(*readPtr) || isdigit(*readPtr)) {
            *writePtr = *readPtr;
            writePtr++;
        }
        readPtr++;
    }
    *writePtr = '\0';
}
int main() {
    char inputString[] = "Hello!123$";
    printf("Original string: %s\n", inputString);
    removeNonAlphanumeric(inputString);
    printf("Cleaned string: %s\n", inputString);
    return 0;
}
Run
#include <iostream>
#include <cctype>
std::string removeNonAlphanumeric(const std::string& str) {
    std::string cleanedString;
    for (char c : str) {
        if (std::islower(c) || std::isdigit(c)) {
            cleanedString += c;
        }
    }
    return cleanedString;
}
int main() {
    std::string inputString = "Hello!123$";
    std::string cleanedString = removeNonAlphanumeric(inputString);
    std::cout << "Original string: " << inputString << std::endl;
    std::cout << "Cleaned string: " << cleanedString << std::endl;
    return 0;
}
Run
public class Main {
    public static String removeNonAlphanumeric(String string) {
        // Use regular expression to remove non-alphanumeric characters
        String cleanedString = string.replaceAll("[^a-z0-9]", "");
        return cleanedString;
    }
    public static void main(String[] args) {
        String inputString = "Hello!123$";
        String cleanedString = removeNonAlphanumeric(inputString);
        System.out.println("Original string: " + inputString);
        System.out.println("Cleaned string: " + cleanedString);
    }
}
Run
import re
def removeNonAlphanumeric(string):
    # Use regular expression to remove non-alphanumeric characters
    cleaned_string = re.sub(r'[^a-z0-9]', '', string)
    return cleaned_string
# Test the function
input_string = "Hello!123$"
cleaned_string = removeNonAlphanumeric(input_string)
print("Original string:", input_string)
print("Cleaned string:", cleaned_string)

Question 4: Minimum steps needed to cover a sequence of points on an infinite grid

The task is to determine the minimum number of steps required to cover a sequence of points on an infinite grid. The infinite grid extends indefinitely in all directions, and each point in the sequence represents a coordinate on the grid.

  • For example
    • Input: points[] = [(1, 1), (2, 2), (2, 3)]
    • Output: 2
    • Explanation:
      From (1, 1) to (2, 2):The x-coordinate increases by 1, and the y-coordinate increases by 1.
      Therefore, we need to take 1 step diagonally to reach the next point.
      Total steps required: 1 step.From (2, 2) to (2, 3):The x-coordinate remains the same, and the y-coordinate increases by 1.
      Therefore, we need to take 1 step vertically to reach the next point.
      Total steps required: 1 step.The total steps required to cover the sequence of points [(1, 1), (2, 2), (2, 3)] on the infinite grid, considering all eight directions of movement, is 1 + 1 = 2 steps.

Input Format: Given sequence of cell positions.

Output Format: Print minimum no. of steps needed to cover a sequence of points.

Run
#include <stdio.h>
#include <stdlib.h>
int min_steps_to_cover(int points[][2], int num_points) {
    if (num_points <= 1) {
        return 0;
    }
    int total_steps = 0;
    int i;
    for (i = 1; i < num_points; i++) { int x_diff = abs(points[i][0] - points[i-1][0]); int y_diff = abs(points[i][1] - points[i-1][1]); total_steps += (x_diff > y_diff) ? x_diff : y_diff;
    }
    return total_steps;
}
int main() {
    int points[][2] = {{1, 1}, {2, 2}, {2, 3}};
    int num_points = sizeof(points) / sizeof(points[0]);
    int steps = min_steps_to_cover(points, num_points);
    printf("Minimum steps required: %d\n", steps);
    return 0;
}
Run
#include <iostream>
#include <vector>
#include <cmath>

int minStepsToCover(const std::vector>& points) {
    int numPoints = points.size();
    if (numPoints <= 1) {
        return 0;
    }
    int totalSteps = 0;
    for (int i = 1; i < numPoints; i++) {
        int xDiff = std::abs(points[i].first - points[i - 1].first);
        int yDiff = std::abs(points[i].second - points[i - 1].second);
        totalSteps += std::max(xDiff, yDiff);
    }
    return totalSteps;
}

int main() {
    std::vector> points = {{1, 1}, {2, 2}, {2, 3}};
    int steps = minStepsToCover(points);
    std::cout << "Minimum steps required: " << steps << std::endl;
    return 0;
}

Run
import java.util.*;

public class Main {
    static int minStepsToCover(List points) {
        int numPoints = points.size();
        if (numPoints <= 1) {
            return 0;
        }
        int totalSteps = 0;
        for (int i = 1; i < numPoints; i++) {
            int xDiff = Math.abs(points.get(i).x - points.get(i - 1).x);
            int yDiff = Math.abs(points.get(i).y - points.get(i - 1).y);
            totalSteps += Math.max(xDiff, yDiff);
        }
        return totalSteps;
    }

    public static void main(String[] args) {
        List points = List.of(new Point(1, 1), new Point(2, 2), new Point(2, 3));
        int steps = minStepsToCover(points);
        System.out.println("Minimum steps required: " + steps);
    }
}

class Point {
    int x;
    int y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

Run
def min_steps_to_cover(points):
    if len(points) <= 1:
        return 0
    total_steps = 0
    for i in range(1, len(points)):
        x_diff = abs(points[i][0] - points[i-1][0])
        y_diff = abs(points[i][1] - points[i-1][1])
        total_steps += max(x_diff, y_diff)
    return total_steps
points = [(1, 1), (2, 2), (2, 3)]
steps = min_steps_to_cover(points)
print("Minimum steps required:", steps)

Question 5 : Sort array after converting elements to their squares

Problem Description :

You are given an array of integers in non-decreasing order. Your task is to sort the array after converting each element to its square.

Write a function ‘sortArrayAfterSquaring’ that takes an array of integers as input and returns the sorted array after converting each element to its square.

  • For example
    • Input: [1, 2, 3, 4, 5]
    • Output: [1, 4, 9, 16, 25]
    • Explanation:
      In this example, the input array is [1, 2, 3, 4, 5]. After squaring each element, we get [1, 4, 9, 16, 25]. The resulting array is then sorted in ascending order, which gives [1, 4, 9, 16, 25]. Finally, the sorted array is printed.

Input Format: Given an sorted array containing positive and negative numbers.

Output Format: Print the sorted array containing the squares of the numbers.

Run
#include <stdio.h>
void squareSort(int arr[], int size) {
    // Calculate squares of each element
    for (int i = 0; i < size; i++) {
        arr[i] = arr[i] * arr[i];
    }
    // Sort the array in ascending order using bubble sort
    for (int i = 0; i < size - 1; i++) {
        for (int j = 0; j < size - i - 1; j++) { if (arr[j] > arr[j + 1]) {
                // Swap elements if they are in the wrong order
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}
int main() {
    int arr[] = {4, 2, 1, 3, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    printf("Original Array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    squareSort(arr, size);
    printf("\nSorted Array after Squaring: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}
Run
#include <iostream>
#include <algorithm>
#include <vector>

void squareSort(std::vector<int>& arr) {
    // Calculate squares of each element
    for (int i = 0; i < arr.size(); i++) {
        arr[i] = arr[i] * arr[i];
    }
    // Sort the array in ascending order
    std::sort(arr.begin(), arr.end());
}

int main() {
    std::vector arr = {4, 2, 1, 3, 5};
    std::cout << "Original Array: ";
    for (int i = 0; i < arr.size(); i++) {
        std::cout << arr[i] << " ";
    }
    squareSort(arr);
    std::cout << "\nSorted Array after Squaring: ";
    for (int i = 0; i < arr.size(); i++) {
        std::cout << arr[i] << " ";
    }
    return 0;
}

Run
import java.util.Arrays;
public class Main {
    public static void squareSort(int[] arr) {
        // Calculate squares of each element
        for (int i = 0; i < arr.length; i++) {
            arr[i] = arr[i] * arr[i];
        }
        // Sort the array in ascending order
        Arrays.sort(arr);
    }
    public static void main(String[] args) {
        int[] arr = {4, 2, 1, 3, 5};
        System.out.print("Original Array: ");
        for (int num : arr) {
            System.out.print(num + " ");
        }
        squareSort(arr);
        System.out.print("\nSorted Array after Squaring: ");
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
Run
def square_sort(arr):
    # Calculate squares of each element
    arr = [num**2 for num in arr]
    # Sort the list in ascending order
    arr.sort()
    return arr

arr = [4, 2, 1, 3, 5]
print("Original List:", arr)
arr_sorted = square_sort(arr)
print("Sorted List after Squaring:", arr_sorted)

FAQs on HP Enterprise Coding Questions

Question 1: What are the roles does HP Enterprise is offering for freshers?

Software Development Engineer, Project Engineer Intern, Game Content Writer, UI / UX Designer and other SDE Role for Specific Languages like C / C++, Golang, etc

Question 2: What should I expect during the interview process?
During the interview process at HP Enterprise, you can expect to be asked a series of questions related to your experience, skills, and qualifications which are needed for the role you are applying for. You will be showcasing your skills like:
  1. Programming languages, including C++, Java, and C
  2. Experience in building libraries and APIs.
  3. Knowledge of the latest gaming trends.
  4. Strong Arts, Designing, and technical skills.
Question 3: Does HP Enterprise offers any training or development programs for new hires?
Yes, HP Enterprise offers a variety of training and development programs for new hires, including Orientation related to the Industry, domain-specific training, and leadership development programs. They mainly focus on guiding the new hires to Upskill themselves and enhance their career goal in the their respective field.

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription