Hexaware Coding Questions

Hexaware Coding Questions

Here on this page, we will practice Hexaware Coding Questions based on previous years’ patterns in different programming languages.

Hexaware Coding Questions 2

Q1. Problem Statement

Kochouseph Chittilappilly went to Dhruv Zplanet, a gaming space, with his friends and played a game called “Guess the Word”. 

Rules of games are –

Computer displays some strings on the screen and the player should pick one string/word if this word matches with the random word that the computer picks then the player is declared as Winner.
Kochouseph Chittilappilly’s friends played the game and no one won the game. This is Kochouseph Chittilappilly’s turn to play and he decided to must win the game. 
What he observed from his friend’s game is that the computer is picking up the string whose length is odd and also that should be maximum. Due to system failure computers sometimes cannot generate odd-length words. In such cases, you will lose the game anyways and it displays “better luck next time”. He needs your help. Check the below cases for a better understanding

Sample Input & Output

  • Sample input 0:
    5   → ( number of strings )
    Hello Good morning Welcome you
  • Sample output 0: morning
  • Explanation: First word that is picked by the computer is morning 
    Hello → 5
    Good → 4
    Morning → 7
    Welcome → 7 
    You → 3

 

  • Sample input 1:
    3
    Go to hell 
  • Sample output 1: Better luck next time 
  • Explanation: Here is no word with odd length so computer confuses and gives better luck next time

Run

#include<bits/stdc++.h>
using namespace std;
 
int main()
{
    int n;
    cin >> n;
    string a, result = "";
    while(n--)
    {
        cin >> a;
        if(a.length() & 1)
            if(a.length() > result.length())
                result = a;
    }
    if(result == "")
        cout << "Better luck next time";
    else
        cout << result;
}
Run
import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String arr[] = new String[n];
        
        for(int i = 0; i < n; i++)
        arr[i] = sc.next();
  
        int len = 0;
        ArrayList oddLength=new ArrayList();
        for(int i = 0; i < n; i++)
        {
            len = arr[i].length();
            if(len%2 == 1)
            oddLength.add(arr[i]);       
        }  
        if(oddLength.size() == 0) 
             System.out.println("Better luck next time");
        else 
        {
            Iterator itr=oddLength.iterator();
            int max = -1;
            String res = "";
            while(itr.hasNext())
            {
                String temp=(String)itr.next();
                if(temp.length() > max)
                {
                    res = temp;     
                    max = temp.length(); 
                }
             }
            System.out.println(res);
        }
    }
}
Run
n = int(input())
L = list(map(str,input().split()))

result = ""

for a in L:
    if (len(a) & 1):
        if len(a) > len(result):
            result = a

if result == "":
    result = "Better luck next time"
 
print(result)

Q2. Problem Statement

Ratan is a crazy rich person. And he is blessed with luck, so he always made the best profit possible with the shares he bought. That means he bought a share at a low price and sold it at a high price to maximize his profit. Now you are an income tax officer and you need to calculate the profit he made with the given values of stock prices each day. You have to calculate only the maximum profit Ratan earned.

Note that: Ratan never goes into loss.

  • Example 1:
    Price = [ 1, 6, 2 ]
    Ratan buys it on the first day and sells it on the second. 
  • Example 2:
    Price = [ 9, 8, 6 ] 
    The Price always went down, Ratan never bought it.

Input Format:
First line with an integer n, denoting the number of days with the value of the stack
Next n days, telling the price of the stock on that very day.

Output Format:
Maximum profit done by Ratan in a single line.

Constraints:
Number of days <=10^8

Sample Input for Custom Testing

  • Sample Input: 7, [ 1, 9, 2, 11, 1, 9, 2 ]
  • Sample Output:  10
  • Explanation: The maximum profit possible is when Ratan buys it in 1 rupee and sells it in 11.
Run
#include<bits/stdc++.h>
using namespace std;

int solve(vector v)
{
    int n = v.size();
    if (n == 0)
        return 0;
    int mx = v[0];
    for (int i = 1; i < n; i++)
        mx = max(mx, v[i]);
    if (mx <= 0)
        return 0;
    int mxSum = 0;
    int cSum = 0;
    for (int i = 0; i < n; i++)
    {
        cSum += v[i];
        if (cSum < 0)
            cSum = 0;
        mxSum = max(mxSum, cSum);
    }
    return mxSum;
}

int main()
{
    int n;
    cin >> n;
    int price[n];
    
    for (int i = 0; i < n; i++)
        cin >> price[i];
        vector diff;
    
    for (int i = n-2; i >=0 ; i--)
        diff.push_back(price[i+1] - price[i]);
    
    int ans = solve(diff);
    
    if(ans < 0)
        cout << 0 << endl;
    else
        cout << ans << endl;
}
Run
import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int price[] = new int[n];
		for(int i = 0; i < n; i++)
		{
			price[i] = sc.nextInt();
		}
		Vector diff = new Vector<>();
		for(int i = n-2; i >= 0; i--)
		{
			diff.add(price[i+1]-price[i]);
		}
		int ans = solve(diff);
		if(ans < 0)
		{
			System.out.println(0);
		}
		else
		{
			System.out.println(ans);
		}
	}
	private static int solve(Vector v)
	{
		int n = v.size();
		if(n == 0)
		{
			return 0;
		}
		int mx = v.get(0);
		for(int i = 1; i < n; i++)
		{
			mx = Math.max(mx, v.get(i));
		}
		if(mx <= 0)
		{
			return 0;
		}
		int mxSum = 0, csum = 0;
		for(int i = 0; i < n; i++)
		{
			csum += v.get(i);
			if(csum < 0)
				csum = 0;
			mxSum = Math.max(csum, mxSum);
		}
		return mxSum;
	}
}
Run
def func(diff):
    n = len(diff)
    if n == 0:
        return 0
    mx = max(diff)
    if mx <= 0:
        return 0
    mxS = 0
    cS = 0
    for i in diff:
        cS += i
        if cS <= 0:
            cS = 0
        mxS = max(cS, mxS)
    return mxS


n = int(input())
arr = []
diff = []
ans = [0]
for i in range(n):
    arr.append(int(input()))
for i in range(n - 1):
    diff.append(arr[i + 1] - arr[i])
ans = func(diff)
if ans < 0:
    print("0")
else:
    print(ans)

Q3. Problem Statement

Frogs are sitting on the x-axis of the plane. The x-axis is represented by a given string. * represents a frog and | represents a stone.
The string consists of only the above-mentioned characters. You are given a start index array and end index array, and calculate the number of frogs between the two stones including the endpoint.
Note – Array is 1 indexed

  • Example:
     s = ” |**|*| ”  
    start Index = [ 1, 1 ]
    end Index = [ 5, 6 ]

For the first pair of indices (1,5), the substrings are “|**|*”. There are 2 stars between a pair of bars. For the second pair of indices (1,6), the substring is  “|**|*|” and there are 2+1=3 stars in between the bars. Both of the answers are returned to the array [2,3].

Constraints

  • 1 <= n <= 105
  • 1 <= Start Index[i] <= end Index[i]
  • Each Character of s is either  ” * ”  or  ” | “

Input Format for Custom testing
First line contains a string S the next line contains an integer n, the no.of elements in startIndex. Each line i of the n subsequent lines contains an integer of the start index. the next line contains an integer n, the no. of elements in end Index. Each line i of the n subsequent lines contains an integer of the end index  

Sample Input for Custom Testing

  • Sample Case 0
    *|*|  → s = ” *|*| ”
    1 → startindex[] size=1
    1 → startindex= 1
    1 → endindex[] size=1
    3 → endindex=3
  • Sample output: 0
  • Explanation: The substring from index =1 to index=3 is “*|*”. there is no consecutive pair of bars in this string.
Run
#include<bits/stdc++.h>
using namespace std;

int main()
{
    string s;
    cin >> s;
    int n;
    cin >> n;
 
    int st[n], ed[n];
    for (int i = 0; i < n; i++)
    {
        cin >> st[i];
        st[i]--;
    }
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> ed[i];
        ed[i]--;
    }
    vector bars;
    for (int i = 0; i < s.length(); i++)
    {
        if (s[i] == '|')
            bars.push_back(i);
    }
 
    for (int i = 0; i < n; i++)
    {
        int idx = lower_bound(bars.begin(),bars.end(),st[i]) - bars.begin();
        st[i] = bars[idx];
 
        idx = lower_bound(bars.begin(),bars.end(),ed[i]) - bars.begin();
        if(idx == 0 || bars[idx]==ed[i])
            continue;
        ed[i] = bars[idx-1];
    }
 
    int sz = s.length();
    int starCt[sz] = {0};
    if(s[0] == '*')
        starCt[0] = 1;
 
    for(int i = 1; i < sz; i++)
    {
        starCt[i] = starCt[i-1] + (s[i]=='*');
    }
 
    for(int i = 0; i < n; i++)
    {
        if(st[i] >= ed[i])
        {
            cout << 0 << endl;
        }
        else
        {
            int ans = starCt[ed[i]];
            if(st[i] > 0)
                ans -= starCt[st[i]-1];
            cout << ans << endl;
        }
    }    
    return 0;
}
Run
import java.util.*;
public  class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        String str = sc.next(); 
        int n = sc.nextInt(); 
        int startIndex[] = new int[n];
        int endIndex[] = new int[n];
        
        for(int i = 0; i < n; i++)
            startIndex[i] = sc.nextInt();
        
        for(int i = 0; i < n; i++)
            endIndex[i] = sc.nextInt();
        
        int count = 0;
        for(int i = 0; i < n; i++)
        {
            count = 0;
            String sub = str.substring(startIndex[i]-1,endIndex[i]);
            int start = sub.indexOf("|");
            int end = sub.lastIndexOf("|");
            for(int j = start; j < end; j++)
                if(sub.charAt(j) == '*')
                    count++; 
            System.out.print(count + " ");
        }
    }
}
Run
s = input()
start = []
end = []
n = int(input())

for i in range(n):  
    start.append(int(input()))

for i in range(int(input())):
    end.append(int(input()))

for i in range(n):
    Str = s[start[i]-1:end[i]]
    print(Str.strip('*').count('*'))

Q4. Problem Statement

Stephan is a vampire. And he is fighting with his brother Damon. Vampires get energy from human blood, so they need to feed on human blood, killing human beings. Stephan is also less inhuman, so he will like to take less life in his hand. Now all the people’s blood has some power, which increases the powers of the Vampire. Stephan just needs to be more powerful than Damon, killing the least human possible. Tell the total power Stephan will have after drinking the blood before the battle.
Note: Damon is a beast, so no human being will be left after Damon drinks everyone’s blood. But Stephan always comes early to the town.

Input Format:
First line with the number of people in the town, n.
Second line with a string with n characters, denoting the one-digit power in every blood.

Output Format:
Total minimum power Stephan will gather before the battle.

Constraints:
n <= 10 ^ 4

  • Sample Input :
    6
    093212
  • Sample output:
    9
  • Explanation: Stephan riches the town and drinks the blood with power 9. Now Damon cannot reach 9 by drinking all the other blood.
Run
#include<bits/stdc++.h>
using namespace std;
 
int main()
{
    int n, sum = 0, sum1 = 0;
    cin >> n;
    string s;
    cin >> s;
    sort(s.begin(), s.end(), greater());
    for(auto i:s)
        sum += (i-'0');
    for(auto i:s)  
    {
        if(sum1 > sum)
            break;
        sum1 += (i-'0');
        sum -= i-'0';
        
    }
    cout << sum1; 
}
Run
import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int  n = sc.nextInt();
        String str = sc.next();
        char arr[] = str.toCharArray();
        int a[] = new int[arr.length];
        for(int i = 0; i < a.length; i++)
            a[i] = Integer.parseInt(arr[i] + "");
 
        Arrays.sort(a);
        int sum = 0;
        for(int i = 0; i < a.length; i++)
            sum = sum + a[i];
 
        int sumA = 0;
        int sumB = sum;
        ArrayList subsetA = new ArrayList();
 
        for(int i = a.length-1; i >= 0; i--)
        {
            sumA = sumA + a[i];
            sumB = sumB - a[i];
            subsetA.add(a[i]);
            if(sumA > sumB)
                break; 
        }
  
        Iterator itr = subsetA.iterator();
        while(itr.hasNext())
        {
            System.out.print((Integer)itr.next());
        }
    }
}
Run
n = int(input())
ar = input()
sorted(ar, reverse=True)
br = []
s = 0
aa = []
for i in ar:
    aa.append(int(i))

su = sum(aa)
while s <= su:
    s += (aa[0])
    su = su - (aa[0])
    br.append(aa.pop(0))
print(sum(br))

Q5. Problem Statement

There are some groups of devils and they split into people to kill them. Devils make People them left as their group and at last the group with maximum length will be killed. Two types of devils are there namely “@” and “$”. People are represented as a string “P”

Input Format:
First line with the string for input

Output Format:
Number of groups that can be formed.

Constraints:
2<=Length of string<=10^9

Most people in the group lie in group 1 with 7 members.

Run
#include<bits/stdc++.h>
using namespace std;
 
int main()
{
    string s;
    cin >> s;
    int a = 0, mx = 0;
    for(int i = 0; i < s.length(); i++)
    {
        a++;
        if(s[i] == '@' || s[i] == '$')
        {
            mx = max(a,mx);a=0;
        }
    }
    cout << mx;
}
Run
import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        str = str.replace("@", " ");
        str = str.replace("$", " ");
        String arr[] = str.split(" ");
        int max = 0;
        for(int i = 0; i < arr.length; i++)
            max = Math.max(max,arr[i].length()); 
        System.out.println(max+1);
    }
}
Run
s = input()
s = s.replace("@", " ").replace("$", " ")
s = s.split()
ans = []
for i in s:
    ans.append(len(i) + 1)
ans[-1] -= 1
print(max(ans))

Q6. Problem Statement

Given a string, return the character that appears the minimum number of times in the string. The string will contain only ASCII characters, from the ranges        ( “a” – “z”, “A” – “Z”, 0 – 9 ), and case matters. If there is a tie in the minimum number of times a character appears in the string return the character that appears first in the string.

Input Format:
Single line with no space denoting the input string.

Output Format:
Single character denoting the least frequent character.

Constraints:
Length of string <=10^6

Sample Input / Output

  • Sample Input: cdadcda
  • Sample Output: c
  • Explanation: C and A both are with minimum frequency. So c is the answer because it comes first with less index.
Run
#include<bits/stdc++.h>
using namespace std;
unordered_map F;
 
int main()
{
    string s;
    int m = INT_MAX;
    cin >> s;
    
    for(auto i:s)
        F[i]++;
    
    for(auto i:F)
        m = min(m,i.second);
    
    for(auto i:s)
    {
        if(F[i] == m)
        {
            cout << i;
            break;
        }
    }
}
Run
import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        char arr[] = str.toCharArray();
        int temp[] = new int[256];
        for(int i = 0; i < arr.length; i++)
        {
            temp[arr[i]]++;
        }
        int min = Integer.MAX_VALUE;
        int index = 0; 
        for(int i = 255; i >= 0; i--)
        {
            if(temp[i] == 0)
                continue;
            min = Math.min(min,temp[i]);
        } 
        for(int i = 0; i < arr.length; i++)
        {
            if(min == temp[arr[i]])
            {
                System.out.println(arr[i]);  
                break;
            }
        }
    }
}
Run
s = input()
ans = []

for i in s:
    ans.append(s.count(i))

print(s[ans.index(min(ans))])

Q7. Problem Statement

Rohit loves to play with sequences so he has given you a sequence to solve. To prove to him that you are a good coder, you accept the challenge. Find the sum of the sequence. Given three integers i, j, k. Find  i + (i+1) + (i+2) + (i+3) … j + (j-1) + (j-2) + (j-3) …….. k

  • Example:
    i=5
    j=9
    k=6

 Sum of all values from i to j and back to k:  5 + 6 + 7 + 8 + 9 + 8 + 7 + 6 = 56

CONSTRAINTS:
 -108 <= i, j, k <= 108
   i, k <= j

 

  • SAMPLE CASE 0:
     0  → i = 0
     5  → j = 5
    -1  → k = -1
  • SAMPLE OUTPUT 0:  24
  • EXPLANATION 0:  0 + 1 + 2 + 3 + 4 + 5 + 4 + 3 + 2 + 1 + 0 – 1 = 24
Run
#include<stdio.h>
#include<stdlib.h>

int main()
{
    int i, j, k;
    float n, s1, s2;
    scanf("%d %d %d", &i, &j, &k);
    n = abs(j-i)+1;
    s1 = (n/2)*(2*i+(n-1));
    n = abs(k-(j-1))+1;
    s2 = (n/2)*(2*(j-1)-(n-1));
    printf("%d",(int)(s1+s2));
    return 0;
}
Run
import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        int i=sc.nextInt();
        int j=sc.nextInt();
        int k=sc.nextInt();
        float n,s1,s2;
        n=Math.abs(j-i)+1 ;
        s1=(n/2)*(2*i+(n-1));
        n=Math.abs(k-(j-1))+1 ;
        s2=(n/2)*(2*(j-1)-(n-1)) ;
        System.out.println((int)(s1+s2));
    }
}
Run
i = int(input())
j = int(input())
k = int(input())
n = abs(j - i) + 1
s1 = (n / 2) * (2 * i + (n - 1))
n = abs(k - (j - 1)) + 1
s2 = (n / 2) * (2 * (j - 1) - (n - 1))
print(int(s1 + s2))

Q8. Problem Statement

The principal has a problem with repetitions. Every time someone sends the same email twice he becomes angry and starts yelling. His assistant filters the mails so that all the unique mails are sent only once, and if someone is sending the same mail again and again, he deletes them. Write a program that will see the list of roll numbers of the student and find how many emails are to be deleted.

  • Sample Input:  6,  [ 1, 3, 3, 4, 3, 3 ]
  • Sample Output: 3
Run
#include<bits/stdc++.h>
using namespace std;
map m;
int main()
{
    int n, a, ans = 0;
    cin >> n;
    while(n--)
    {
        cin >> a;
        m[a]++;
        if(m[a] > 1)
            ans++;
    }
    cout << ans;
}
Run
import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        TreeSet  list = new TreeSet <> ();
        for(int i = 0; i < n; i++)
            list.add(sc.nextInt()); 
        System.out.println(Math.abs(n - list.size()));
    }
}
Run
def countDuplicate(numbers):
    c = 0
    for i in set(numbers):
        if numbers.count(i) > 1:
            c += numbers.count(i) - 1
    return c


n = int(input())
numbers = []
for i in range(n):
    numbers.append(int(input()))
print(countDuplicate(numbers))

Q9. Problem Statement

There is an id code that is supposed to be given to all the aspirants of an exam. It is a substring of a given string. That means, the authority takes a string and then assigns all the unique substrings to all the students. Suppose there is a string “abcde”, so the ids of the students will be “a”, “b”, “c”, “d”, “e”, “ab”, “abc”, “abcd”, “abcde”, ” bc”, “bcd”, “bcde”, “cd”, “cde”, “de”.
The students are standing in a line according to the lexicographic order of their given ids. You have to find out the id of the last student for the given input string from which the ids are generated.

Input Format:
Single line with the id generating string

Output format:
The last id as per lexicographical order

Constraints:
Number of characters in the string<=10^9

  • Sample Input: abdc
  • Sample output: dc
  • Explanation: The last student will be with the id dc. The order will be
    abdc
    a
    ab
    abd
    abdc
    b
    bd
    bdc
    c
    d
    dc
Run
#include<bits/stdc++.h>
using namespace std;
 
int main()
{
    string s;
    cin >> s;
    vector  v;
    for(int i = 0; i < s.length(); i++)
    {
        v.push_back(s.substr(i, s.length()-i));
    }
    sort(v.begin(),v.end(),greater());
    cout << v[0];
 
}
Run
import java.util.*;
public class Main
{
    public static String maxString(char set[])
    {
        int n=set.length;
        String temp="";
        TreeSet list=new TreeSet<>();
        for(int i = 0; i < n; i++)
        {
            temp="";
            for(int j = i; j < n; j++)
            {
                temp=temp+set[j];
                list.add(temp);
            }
        }  
        return list.last();
    }
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        String str=sc.next();
        char arr[]=str.toCharArray();
        System.out.println(maxString(arr));
    }
}
Run
s = input()
j = 1
c = 0
while j < len(s):
    if ord(s[c]) < ord(s[j]):
        c = j
    j += 1
print(s[c:])

Q10. Problem Statement

You are given an array, You have to choose a contiguous subarray of length ‘k’, and find the minimum of that segment, return the maximum of those minimums.

  • Sample Input:
    1 →  Length of segment x =1
    5 →  size of space n = 5
    1 → space = [ 1,2,3,1,2]



  • Sample Output: 3
  • Explanation: The subarrays of size x = 1 are [1],[2],[3],[1], and [2],Because each subarray only contains 1 element, each value is minimal with respect to the subarray it is in. The maximum of these values is 3. Therefore, the answer is 3.
Run
#include<bits/stdc++.h>
using namespace std;
vector arr;
int prevmin = -1;
int flag = 0;
int x, n, q;

int sorting(int start,int end)
{
    if(start + 1 == n)
    {
        start=0;
        end=end-n;
    }
    if(start==end)
        return arr[start];
    
    return min(arr[start],sorting(start+1,end));
}

int func(int start,int end)
{
    if(flag==0)
    {
        flag++;
        return prevmin = sorting(start,end);
    }
    if(arr[start-1]==prevmin)
        return prevmin;
    
    return prevmin= (arr[end] <= prevmin) ? prevmin:sorting(start,end);
}

int main()

{
    cin >> x >> n;
    int ans = 0;
    for(int i = 0; i < n; i++)
    {  
        cin >> q;
        arr.push_back(q);
    }
    for(int i = 0; i < n; i++)
    {
        ans=max(ans,func(i,i+x-1));
    }
    cout << ans;
}
Run
import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        int n = sc.nextInt();
        int arr[] = new int[n];
        for(int i = 0; i < n; i++)
            arr[i] = sc.nextInt();

        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;

        for(int i = 0; i <= n - x; i++)
        {
            min = Integer.MAX_VALUE;
            for(int j = i; j< ( i + x ); j++)
                min = Math.min(min,arr[j]);
            max = Math.max(min,max);     
        }
        System.out.println(max);
    }
}
Run
s = int(input())
n = int(input())
a = []
for i in range(n):
    a.append(int(input()))


def min_in_segment(start, end, prev, s, prev_min):
    if s == 1:
        return a[start]
    else:
        if prev == -1 or prev_min == -2:
            return min(a[start:end + 1])
        elif prev_min != -2:
            if prev != prev_min:
                if a[end] < prev_min:
                    return a[end]
                else:
                    return prev_min
            else:
                return min(a[start:end + 1])


msf = -1
prev = -1
prev_min = -2
for i in range(n - s + 1):
    new_min = min_in_segment(i, i + s - 1, prev, s, prev_min)
    msf = max(msf, new_min)
    prev = a[i]
    prev_min = new_min
print(msf)