InfyTQ Coding Questions With Solutions 2024 (Latest) | InfyTQ Coding Questions & Answers 2024

InfyTQ Coding Questions With Solutions 2024 | InfyTQ Coding Questions and Answers | InfyTQ Coding Questions For Freshers | InfyTQ Coding Questions in Java | InfyTQ Coding Questions in C++ | InfyTQ Coding Questions in Python

InfyTQ Coding Questions With Solutions 2024: InfyTQ will conduct the Coding Test for each hiring Process. Every year, they hire many employees to fill many positions. As of now, they are going to hold the test for the InfyTQ Coding. So, aspirants who are going to attend this hiring process kindly check out the InfyTQ Coding Questions & Answers before attending the process.

It is very important for all the contenders to before good before the Test. We have provided the sample InfyTQ Coding Questions & Answers for your preparation process. With the help of this preparation good on the coding test & score good marks. If you qualify in this round only you may continue to attend the selection process, so read the article properly to get detailed information about the InfyTQ Previous Coding Questions. More details like Cut Off, Salary, Hike, Increment, Annual Appraisal, etc. are available on this page

InfyTQ Coding Questions and Answers

Q) You have been given a string S of length N. The given string is a binary string that consists of only 0’s and ‘1’s. Ugliness of a string is defined as the decimal number that this binary string represents.

 Example:

  • “101” represents 5.
  • “0000” represents 0.
  • “01010” represents 10.

There are two types of operations that can be performed on the given string.

  • Swap any two characters by paying a cost of A coins.
  • Flip any character by paying a cost of B coins
  • flipping a character means converting a ‘1’to a ‘0’or converting a ‘0’ to a ‘1’.

Initially, you have been given coins equal to the value defined in CASH. Your task is to minimize the ugliness of the string by performing the above mentioned operations on it. Since the answer can be very large, return the answer modulo 10^9+7.

Note:

  • You can perform an operation only if you have enough number of coins to perform it.
  • After every operation the number of coins get deducted by the cost for that operation.

Input Format

  • The first line contains an integer, N, denoting the number of character in the string
  • The next line contains a string, S, denoting the the binary string
  • The next line contains an integer, CASH, denoting the total number of coins present initially
  • Next will contains an integer, A, denoting the cost to swap two characters.
  • Then the next line contains an integer, B, denoting the cost to flip a character.

Constraints

  • 1 <= N <= 10^5
  • 1< len(S)<= 10^5
  • 1<=CASH <=10^5
  • 1<=A<=10^5
  • 1<=B<=10^5

Sample Input 1 :

4
1111
7
1
2

  Sample Output 1 :

1

  Explanation:

3 flips can be used to create “0001” which represents 1.

  Sample Input 2:

6
111011
7
1
3

  Sample Output 2:

7

  Explanation:

First swap 0 with the most significant 1, then use flip twice first on index one and then on index two “111011”=>”0111111″=>”001111″=>”000111″ the value represented is 7.

  Sample Input 3:

6
111011
7
3
2

  Sample Output 3:

3

 Explanation:

Flip the 3 most significant characters to get “000011” : the value represented by this string is 3.N

EXAMPLE PROGRAMS

C++ PROGRAM

#include<bits/stdc++.h>
using namespace std;
string s;
int n, cash, a, b;

void swapf ()
{
  int i;

  for (int a = 0; a < s.length (); a++) 
  if (s[a] == '1') 
  { 
      i = a; 
      break; 
      
  } 
  int j = s.length () - 1; 
  while (j > i)
    {
      if (cash < a)
	break;

      if (s[j] == '0')
	{
	  if (s[i] == '0')
	    i++;

	  else
	    {
	      swap (s[i], s[j]);
	      cash -= a;
	      j--;
	    }
	}
      else
	j--;
    }
}
void flipf ()
{
  int i;
  for (int a = 0; a < s.length (); a++) 
  if (s[a] == '1') 
  { 
      i = a; break; 
      
  } 
  while (cash >= b)
    {

      if (i == s.length ())
      break;

      if (s[i] == '1')
	{
	  s[i] = '0';
	  i++;
	  cash -= b;
	}
    }
}

int main ()
{
  cin >> n >> s >> cash >> a >> b;

  if (a < b)
    {
      swapf ();
      flipf ();
    }

  else
    {
      flipf ();
      swapf ();
    }

  cout << stoull (s, 0, 2);

}

JAVA PROGRAM

import java.util.*;
class Main
{
  static String str;
  static int cash, n, a, b;
  static void swapf ()
  {
    char s[] = str.toCharArray ();
    int i = 0;
    for (int a = 0; a < s.length; a++)
      if (s[a] == '1')
	{
	  i = a;
	  break;
	}
    int j = s.length - 1;
    while (j > i)
      {
	if (cash < a)
	  break;
	if (s[j] == '0')
	  {
	    if (s[i] == '0')
	      i++;
	    else
	      {
		char temp = s[i];
		s[i] = s[j];
		s[j] = temp;
		cash -= a;
		j--;
	      }
	  }
	else
	  j--;
      }
    str = new String (s);
  }
  static void flipf ()
  {
    char s[] = str.toCharArray ();
    int i = 0;

    for (int a = 0; a < s.length; a++)
      if (s[a] == '1')
	{
	  i = a;
	  break;
	}
    while (cash >= b)
      {
	if (i == s.length)
	  break;
	if (s[i] == '1')
	  {
	    s[i] = '0';
	    i++;
	    cash -= b;
	  }
      }
    str = new String (s);
  }

  public static void main (String[]args)
  {
    Scanner sc = new Scanner (System.in);
    n = sc.nextInt ();
    str = sc.next ();
    cash = sc.nextInt ();
    a = sc.nextInt ();
    b = sc.nextInt ();

    if (a < b)
      {
	swapf ();
	flipf ();
      }
    else
      {
	flipf ();
	swapf ();
      }
    System.out.println (Integer.parseInt (str, 2));
  }
}

Q): While playing an RPG game, you were assigned to complete one of the hardest quests in this game. There are monsters you’ll need to defeat in this quest. Each monster is described with two integer numbers – poweri and bonusi. To defeat this monster, you’ll need at least poweri experience points. If you try fighting this monster without having enough experience points, you lose immediately. You will also gain bonusi experience points if you defeat this monster. You can defeat monsters in any order.

The quest turned out to be very hard – you try to defeat the monsters but keep losing repeatedly. Your friend told you that this quest is impossible to complete. Knowing that, you’re interested, what is the maximum possible number of monsters you can defeat?

Input:

  • The first line contains an integer, n, denoting the number of monsters. The next line contains an integer, e, denoting your initial experience.
  • Each line i of the n subsequent lines (where 0 ≤ i < n) contains an integer, poweri, which represents power of the corresponding monster.
  • Each line i of the n subsequent lines (where 0 ≤ i < n) contains an integer, bonusi, which represents bonus for defeating the corresponding monster.

Output

  • 2

Example Programs:

JAVA PROGRAM

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

class Main
{
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int exp = s.nextInt();

        int monst[] = new int[n];
        int bonus[] = new int[n];

        for (int i = 0; i < n; i++) {
            monst[i] = s.nextInt();
        }
        for (int i = 0; i < n; i++) {
            bonus[i] = s.nextInt();
        }

        class Monster {
            private final int power, bonus;
            public Monster(int power, int bonus){
                this.power = power;
                this.bonus = bonus;
            }
        }

        Monster[] monsters = new Monster[n];

        for(int i = 0; i < n; i++)
            monsters[i] = new Monster(monst[i], bonus[i]);

        Arrays.sort(monsters, Comparator.comparingInt(m -> m.power));

        int count = 0;

        for(Monster m: monsters){
            if(exp < m.power) break;
            exp += m.bonus;
            ++count;
        }
        System.out.println(count);
    }
}
n = int(input())
lev = int(input())
p = []
b = []
a = []
ans = 0
for i in range(n):
   p.append(int(input()))
for j in range(n):
   b.append(int(input()))
for k in range(n):
   a.append([p[k], b[k]])
a.sort()
for z in a:
   if z[0] > lev:
       break
   lev += z[1]
   ans += 1
print(ans)

Q) Henry is extremely keen on history and every one of the ages of his family. He does a ton of exploration and understands that he has plummeted from the incomparable Amaya line. After a ton of looking through old records and the most recent records of the general public, he can discover all the parent-kid connections in his family right from the extraordinary ruler Ming of the tradition to himself.

These connections are given in the structure of a direct exhibit where the emperor is at the main position and his kids are at pos (2i + 1) and (2i + 2)

This is the pattern followed throughout.

Henry needs to sort out every one of the kin of individual X from the information.

Write a program for Henry to figure out all the siblings of person X from the data.
Return the sorted list of all of Henry’s siblings.

If no sibling return {-1}

  • input 1: N, the length of the array
  • input2: An array representing the ancestral tree
  • input 3: X, the person whose siblings are sought.
  • output – return the array of all siblings in increasingly sorted order.

Example 1 :

input 1: 5
input 2: {1,2,3,4,5}
input 3: 1
output: {-1}
Explanation: x is the root of the tree and has no siblings

Example 2 :

input 1: 6
input 2: {1,2,3,4,5,6}
input 3: 5
output: {4,6}
Explanation: {2,3 } are the children of {1}. {4,5,6 } are the children of {2,3}, thus the siblings of x= 5 are {4,6}

JAVA PROGRAM

import java.util.*;
 
public class Main
{
    Node root;
    static class Node
    {
        int data;
        Node left, right;
    
        Node (int data) 
        {
            this.data = data;
            this.left = null;
            this.right = null;
        } 
    } 

    public static void main (String[]args)
    {
        Main t2 = new Main ();
        Scanner sc = new Scanner (System.in);
        int length = sc.nextInt ();
        int arr[] = new int[length];
    
        for (int i = 0; i < length; i++)
        {
            arr[i] = sc.nextInt ();
        }
        int target = sc.nextInt ();
        t2.root = t2.insertLevelOrder (arr, t2.root, 0);
    
        Set < Integer > sets = t2.levelOrderBottom (t2.root, target);
        sets.remove (target);
        System.out.println (sets);
    }   
    public static Node insertLevelOrder (int[]arr, Node root, int i) 
    {
        if (i < arr.length)
        {
            Node temp = new Node (arr[i]);
            root = temp;
            root.left = insertLevelOrder (arr, root.left, 2 * i + 1);
            root.right = insertLevelOrder (arr, root.right, 2 * i + 2);
        }
        return root;
    }

    public Set < Integer > levelOrderBottom (Node root, int target)
    {
        if (root == null)
        {
        	return null;
        }
        Queue < Node > q = new LinkedList <> ();
        q.offer (root);
    
        while (!q.isEmpty ())
        {
            int qsize = q.size ();
            Set < Integer > temp = new HashSet <> ();
            
            for (int i = 0; i < qsize; i++)
	        {
                Node child = q.poll ();
                temp.add (child.data);
                
                if (child.left != null)
	            {
                    q.offer (child.left);
                }
                if (child.right != null)
	            {
                    q.offer (child.right);
                }
            }
            if (temp.contains (target))
                return temp;
        }
        return null;
    }
}

PYTHON PROGRAM

def identify_siblings(tree_array, x):
    tree_len = len(tree_array)
    index = tree_array.index(x)
    level = 0
    start_index = level
    number_of_nodes = 0
    while start_index < tree_len:
    	end_index = pow(2, level) + start_index
    	if x in tree_array[start_index:end_index]:
    		break
    	level += 1
    	start_index = (2 * start_index) + 1
    final_array = tree_array[start_index:end_index]
    final_array.remove(x)
    return final_array if final_array else [-1]

n = int(input())
arr = []
for i in range(n):
    arr.append(int(input()))
x = int(input())
print(identify_siblings(arr, x))

Question) You want to buy a particular stock at its lowest price and sell it later at its highest price. Since the stock market is unpredictable, you steal the price plans of a company for this stock for the next N days.
Find the best price you can get to buy this stock to achieve maximum profit.

Note: The initial price of the stock is 0.

Input Specification:

Input1: N, number of days
Input2: Array representing change in stock price for the day.

Output Specification:

Your function must return the best price to buy the stock at.

Example1:

Input1: 5
Input2: (-39957,-17136,35466,21820,-26711}
Output: -57093
Explanation: The best time to buy the stock will be on Day 2 when the price of the stock will be -57093.

Example2:

Input1: 5
Input2: (-39957, -17136, 1, 2, -26711)
Output: -80801
Explanation: The best time to buy the stock will be on Day 5 when the price of the stock will be -83801.

Example3:

Input1: 9
Input2: (-4527,-1579,-38732,-43669,-9287,-48068,-30293,-30867,18677}
Output: -207022
Explanation: The best time to buy the stock will be on Day 8 when the price of the stock will be -207022.

C++ PROGRAM:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int N, ans, price;
    cin>>N;
   
    int arr[N];
    
    for (int i = 0; i < N; i++)
        cin>>arr[i];
    
    price = 0;
    ans = 0;
    for (int i = 0; i < N; i++)
    {
        price = price + arr[i];
        if (ans > price)
            {
                ans = price;
            }
    }
    cout << ans;
}

C PROGRAM:

#include<stdio.h>
int main()
{
    int N, ans, price;
    scanf("%d", &N);
   
    int arr[N];
    
    for (int i = 0; i < N; i++)
        scanf("%d", &arr[i]);
    
    price = 0;
    ans = 0;
    for (int i = 0; i < N; i++)
    {
        price = price + arr[i];
        if (ans > price)
            {
                ans = price;
            }
    }
    printf("%d", ans);
}

PYTHON PROGRAM

n = int(input())
arr = []
for i in range(n):
   arr.append(int(input()))
min = 0
for i in range(1, n):
   if sum(arr[:i]) < min:
       min = sum(arr[:i])
print(min)

InfyTQ Coding Questions With Solutions For C

Question: Lazy String

Problem Statement-:  Anish is the laziest person you can ever see. He is tasked to write the name of the winner in a game where two people take part. And he just writes the longest common subsequence over there, so that with minimum change or no backspace he can edit the name to the winner’s name.

For two given names, you have to predict what Anish will write in his computer before the start of the name. If there are more than two longest subsequences possible, write the one with less lexicographic value.

Input Format:

  • Two lines including two strings of names (All with capital letters)

Output Format:

  • A single line with the lexicographically smallest possible longest common subsequence.

Sample Input:

ABCD
BACD

Sample Output:

ACD

Explanation:

ACD and BCD these are the two possible biggest substring

C++ PROGRAM

#include <bits/stdc++.h>
using namespace std;
string s1,s2,s3;
 
int fun(int i,int j,int k,string s)
{
    if(i==s1.length()||j==s2.length())
    {
        if(s3.length()==s.length()) s3=min(s,s3);
        else if(s3.length()<s.length()) s3=s;
        return k;
    }
    if(s1[i]==s2[j]) return fun(i+1,j+1,k+1,s+s1[i]);
    return max(fun(i+1,j,k,s),fun(i,j+1,k,s));
}
 
int main()
{
    cin>>s1>>s2;
    fun(0,0,0,"");
    cout<<s3;
}

JAVA PROGRAM

import java.util.Scanner;
public class Application19 {
	public static String s1,s2,s3="";
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		 s1 = sc.nextLine();
		 s2 = sc.nextLine();
		 fun(0,0,0,"");
		 System.out.println(s3);
	}
	private static int fun(int i, int j, int k, String s) {
		// TODO Auto-generated method stub
		if(i==s1.length() || j==s2.length()) {
			if(s3.length()==s.length()) {
				if(s3.compareTo(s)>0) {
					s3=s;
				}
			}
			else if(s3.length()<s.length()) {
				s3=s;
			}
			return k;	
		}
		if(s1.charAt(i)==s2.charAt(j)) {
			return fun(i+1,j+1,k+1,s+s1.charAt(i));
		}
		return Math.max(fun(i+1,j,k,s), fun(i,j+1,k,s));
	}

}

PYTHON PROGRAM

s1=input()
s2=input()
s3=""
def fun(i,j,k,s):
    global s1
    global s2
    global s3
    if i==len(s1) or j==len(s2):
        if len(s3)==len(s):
            s3=min(s,s3)
        elif len(s3)<len(s):
            s3=s
        return k 
    if s1[i]==s2[j]:
        return fun(i+1,j+1,k+1,s+s1[i])
    return max(fun(i+1,j,k,s),fun(i,j+1,k,s))
    
fun(0,0,0,"")
print(s3)

Question: Corona for Computer

Problem Statement-: Every decimal number can be changed into its binary form. Suppose your computer has it’s own CoronaVirus, that eats binary digits from the right side of a number. Suppose a virus has 6 spikes, it will eat up 6 LSB binary digits in your numbers.

You will have a bunch of numbers, and your machine will have a virus with n spikes, you have to calculate what will be the final situation of the final numbers.

Input Format:

  • First line, a single Integer N
  • Second line N space separated integers of the bunch of values as array V
  • Third line a single integer n, the number of spikes in Corona for Computer

Output Format:

  • Single N space separated integers denoting the final situation with the array v.

Sample Input:

5

1 2 3 4 5

2

Sample Output:

0 0 0 1 1

Explanation: 

5 is 101 in binary, when you cut the last two binary digits, its 1.

C++ PROGRAM

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int N,n;cin>>N;
    vector<int> v(N);
    for(int i=0;i<N;i++) cin>>v[i];
    cin>>n;
    for(auto i:v)
    cout<<(i>>n)<<" ";
}

JAVA PROGRAM

import java.util.Scanner;

public class Application16 {

 public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  int n = sc.nextInt();
  int arr[]=new int[n];
  for(int i=0;i<n;i++) {
   arr[i] = sc.nextInt();
  }
  int k = sc.nextInt();
  for(int i:arr) {
   System.out.print((i>>k));
   System.out.print(" ");
  }
 }

}

PYTHON PROGRAM

N=int(input())
a=list(map(int,input().split()))
n=int(input())
s=""
for i in a:
    s+=str(i>>n)+" "
print(s)

Question: Help of Prepsters

Problem Statement-: Arnab has given me a challenge. I have to calculate the number of numbers which are less than a certain value n, and have exactly k set bits in its binary form. As you are a Prepster like me, help me write a code that will take input for n and k and give the expected output.

Constraints :

  • 1<=n<=10000
  • 1<=k<=10

Input Format :

  • First line containing n and k space separated

Output Format :

  • Number of numbers present in a single line

Sample Input:

7 2

Sample Output:

3

Explanation:

011,110,101 -> These three numbers.

C++ PROGRAM

#include <bits/stdc++.h>
using namespace std;
int n,k,ans,l;
map<int,int> m;
 
void func(int i,string s,int L)
{
   // cout<<s<<endl;
    if(L>l) {return;}
    if(i==0 && m[stoull(s,0,2)]==0) {m[stoull(s,0,2)]++;ans++;}
    if(s!="") if(n<stoull(s,0,2)) {return;}
    func(i-1,s+"1",L+1);
    func(i,s+"0",L+1);
}
 
int main()
{
    cin>>n>>k;char res[10000];itoa(n,res,2);
    ans=0;l=strlen(res);
    func(k-1,"1",1);
    cout<<ans;
}

JAVA PROGRAM

import java.util.Scanner;

public class Application17 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int k = sc.nextInt();
		int ans=0;
		for(int i=1;i<n;i++) {
			if(countSetBits(i)==k) {
				ans++;
			}
		}
		System.out.println(ans);
	}

	private static int countSetBits(int i) {
		if(i==0)
		return 0;
		else
			return 1 + countSetBits(i&(i-1));
	}

}

PYTHON PROGRAM

ans=0
n,k=map(int,input().split())
l=len(bin(n)[2:])
def func(i,s,L):
    global l 
    global ans
    if(L>l):
        return
    if i==0 :
        ans+=1 
    if s!="":
        if n<int(s,2):
            return
    func(i-1,s+"1",L+1)
    func(i,s+"0",L+1)
    


func(k-1,"1",1)
print(ans)

InfyTQ Coding Questions With Solutions For Java

Question: Momentum LinkedList

Problem Statement:  Ratul made a linked list, a list made of n nodes, where every node has two variables, the velocity and the mass of a particle.

Since all the particles have the velocity in the same direction, find the total momentum of the entity made by the particles from the linked list.

Constraints :

  • 1<=n<=10000
  • 1<=m,v<=100

Input format:

  • First line containing n, number of nodes
  • Then n lines containing the mass and the velocity space separated.

Output Format:

  • Single integer denoting the momentum

Sample Input:

4

1 3

2 4

2 3

4 5

Sample Output:

37

C++ PROGRAM

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int n,s=0,m,v;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>m>>v;
        s+=(m*v);
    }
    cout<<s;
}

JAVA PROGRAM

import java.util.Scanner;

public class Application18 {

 public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  int n = sc.nextInt();
  int s = 0;
  for(int i=0;i<n;i++) {
   int m=sc.nextInt();
   int v= sc.nextInt();
   s+=(m*v);
  }
  System.out.println(s);
 }

}

PYTHON PROGRAM

n=int(input())
s=0
for i in range(n):
    m,v=map(int,input().split())
    s+=(m*v)
print(s)

Question: Class Monitor

Problem Statement: After JEE Mains, some students got admission into an engineering college. Now there is a class consisting of such n students, and the HOD came to say it is time to select the class monitor. But He never gets all of them at one time. So he brought a register, every time he gets someone with less rank than the previous time he cut the name and wrote the name of the student and the rank.

For a given number of ranks he gets each time, you have to predict how many names are cut in the list.

Constraints:

  • Number of Visiting<=10^9
  • ranks <=10000

Input Format:

  • Number of Visiting N in their first line
  • N space separated ranks the HOD gets each time

Output Format:

  • Number of ranks cut in the list

Sample Input:

6

4 3 7 2 6 1

Sample Output:

3

C++ PROGRAM

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int n,p,m=INT_MAX,ans=0;
    cin>>n;
    vector<int> a(n);
    for(int i=0;i<n;i++)
    {
        cin>>p;
        if(p<m) {m=p;ans++;}
    }
    cout<<ans-1;
}

JAVA PROGRAM

import java.util.Scanner;

public class Application15 {

 public static void main(String[] args) {
  int n,p,ans=0,m=Integer.MAX_VALUE;
  Scanner sc = new Scanner(System.in);
  n = sc.nextInt();
  for(int i=0;i<n;i++) {
   p = sc.nextInt();
   if(p<m) {
    m=p;
    ans++;
   }
  }
  System.out.print(ans-1);
 }
}

PYTHON PROGRAM

n=int(input())
a=list(map(int,input().split()))
m=a[0]
ans=0
for i in range(1,n):
    if a[i]<m:
        m=a[i]
        ans+=1
print(ans-1)

Question: Profit Balance

Problem Statement-: Anand and Brijesh got a bunch of profit in their business. Now it’s time to divide the profit between themselves. Anand being the one with the calculator was the one who could decide who will get how much. But as he was one hell of an honest guy, he can’t cheat on Brijesh to get some extra money. So he decided to divide them in such a way where they can get almost the same amount possible. Although, it is sometimes impossible to divide the profit into two, because the profits must be written in their production managed copy in a way where you cannot share the profit of a single thing, A single Profit will be held by a single person.

You are the one who is called to mitigate the problem. Given an array of profit, find out in the process, what can be the minimum difference between them in terms of income.

Constraints:

  • 1<=N<=10^3
  • 0<=Profits<=1000

Input Format:

  • First line contains an integer N, number of profits.
  • Next line, N space separated Integers denoting the i-th Profit.

Output:

  • A single integer denoting minimum possible difference between the total profits.

Sample Input:

4

1 2 3 4

Output:

0

Explanation:

He will take 1 and 4, so his profit will be 5, so the difference will be 0.

C++ PROGRAM

#include<bits/stdc++.h>
using namespace std;
vector<int> arr;
int n,s;
map<int,map<int,int>> m;
 
int MinDif(int i,int ss)
{
    if(m[i][ss]) return m[i][ss];
    if(i==n) return m[i][ss]= abs(s-2*ss);
    if(ss>=s/2) return m[i][ss]=abs(s-2*ss);
    return m[i][ss]=min(MinDif(i+1,ss+arr[i]),MinDif(i+1,ss));
}
 
int main()
{
    cin>>n;int a;
    s=0;
    for(int i=0;i<n;i++)
    {cin>>a;arr.push_back(a);s+=a;}
    cout<<MinDif(0,0);

JAVA PROGRAM

import java.util.HashMap;
import java.util.Scanner;
public class Application14 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int s=0;
		int arr[]=new int[n];
		for(int i=0;i<n;i++) {
			arr[i] = sc.nextInt();
			s+=arr[i];
		}
		HashMap<Integer,HashMap<Integer,Integer>> m = new HashMap<>();
		System.out.println(minDiff(0,0,s,n,m,arr));
	}
	private static int minDiff(int i, int j, int s, int n, HashMap<Integer, HashMap<Integer, Integer>> m, int[] arr) {
		if(m.containsKey(i)) {
			if(m.get(i).containsKey(j))
			return m.get(i).get(j);
		}
		if(i==n) {
			HashMap<Integer,Integer> z = new HashMap<>();
			z.put(j,  Math.abs(s-2*j));
			m.put(i,z);
			return m.get(i).get(j);
		}
		if(j>=s/2) {
			HashMap<Integer,Integer> z = new HashMap<>();
			z.put(j,  Math.abs(s-2*j));
			m.put(i,z);
			return m.get(i).get(j);
		}
		int temp = Math.min(minDiff(i+1,j+arr[i],s,n,m,arr), minDiff(i+1,j,s,n,m,arr));
		HashMap<Integer,Integer> z = new HashMap<>();
		z.put(j, temp);
		m.put(i, z);
		return m.get(i).get(j);
	}
}

PYTHON PROGRAM

from collections import defaultdict
m = defaultdict(lambda: defaultdict(int))
def MinDif(i,ss,a,n,m):
    global s
    if m[i][ss] != 0:
        return m[i][ss]
    if i==n:
        m[i][ss]=abs(s-(2*ss))
        return m[i][ss]
    if ss>=s//2:
        m[i][ss]=abs(s-(2*ss))
        return m[i][ss]
    m[i][ss]=min(MinDif(i+1,ss+a[i],a,n,m),MinDif(i+1,ss,a,n,m))
    return m[i][ss]


n=int(input())
a=list(map(int,input().split()))
s=sum(a)
print(MinDif(0,0,a,n,m))

InfyTQ Coding Questions With Solutions For Python

Question: Even Odd Even Odd 

Problem Statement -:  A number is even odd special if and only if there are even digits side by side, same goes for odd digits too. So the distributions must be in an alternating basis of even digits and odd digits. You are given a number N, and you have to say how many special numbers are possible <=N, and are greater than 0.

Constraints:

  • 1<=N<=10^8

Input Format:

  • First Line containing a single integer N.

Output Format:

  • Single line containing a single integer denoting the possible number of special numbers.

Sample Input:

30

Output:

20

Explanation:

20 such special numbers are there:-

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 21, 23, 25, 27, 29, 30

C++ PROGRAM

#include<bits/stdc++.h>
using namespace std;
int ans;
int a,l;
void func(string s)
{
    int S=stoi(s);
    if(a>=S)
    {
        cout<<s<<endl;
    ans++;}
    if(s.length()==l) {
     return;
    }
    if ((S%10)&1)
    for(int i=0;i<9;i+=2)
    func(s+to_string(i));
    else
    for(int i=1;i<=9;i+=2)
    func(s+to_string(i));
}
 
int main()
{
    string s;
    cin>>s;ans=0;
    l=s.length();
     a=stoi(s);
    for(int i=2;i<9;i+=2)
    func(to_string(i));
    for(int i=1;i<=9;i+=2)
    func(to_string(i));
    cout<<ans;
}

PYTHON PROGRAM

a=input()
ans=0
l=len(a)
def func(s):
    global ans
    global a
    global l
    S=int(s)
    if int(a)>=S:
        ans+=1 
    if len(s)==l:
        return
    if (S&1):
        for i in range(0,9,2):
            func(s+str(i))
    else:
        for i in range(1,10,2):
            func(s+str(i))
    
    
    
for i in range(2,9,2):
    func(str(i))
for i in range(1,10,2):
    func(str(i))
print(ans)

Question: Sentence counter

Problem statement:  We know sentences are terminated with certain punctuations like ‘.’,’!’,’?’, whereas there are several punctuations which don’t terminate the punctuations. Given for a paragraph, write a code to find out how many sentences are there.

Note that, ‘…’,’,’,’-‘ these don’t terminate a sentence.

Constraints: 

  • Number of words in the paragraph<=10^8

Input Format:

  • Paragraph ended with an enter.

Output Format:

  • Single Integer denoting number of sentences.

Sample Input:

Hello! How are you? Last time I saw you… you were nervous.

Sample Output:

3

Explanation:

The three sentences are:

hello!

How are you?

Last time I saw you… you were nervous.

C++ PROGRAM

#include <bits/stdc++.h>
using namespace std;
 
int SentenceCount(string s)
{
    istringstream ss(s);
    int ans=0;
    while(ss)
    {
        string w;ss>>w;
        if(w=="") break;
        if(w[w.length()-1]=='!'||w[w.length()-1]=='?') ans++;
        else if(w==".") ans++;
        else if(w.length()>1)
        if(w[w.length()-1]=='.'&&w[w.length()-2]!='.') ans++;
    }
    return ans;
}
 
int main()
{
    string s;
    getline(cin,s);
    cout<<SentenceCount(s);
}

JAVA PROGRAM

import java.util.Scanner;
public class Application12 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s = sc.nextLine();
		System.out.println(sentenceCount(s));
	}
	private static int sentenceCount(String s) {
		String[] w = s.trim().split("\\s+");
		int ans=0;
		for(int i=0;i<w.length;i++) {
			String k = w[i];
			int len = k.length();
			if(k.lastIndexOf('!')==(len-1) || k.lastIndexOf('?')==(len-1) ) {
				ans++;
			}else if(k.equals(".")) {
				ans++;
			}else if(len>1) {
				if(k.charAt(len-1)=='.'&&k.charAt(len-2)=='.') {
					ans++;
				}
			}else {	
			}
		}
		return ans;
	}
}

PYTHON PROGRAM

def SentenceCount(L):
    ans=0
    for w in L:
        if w[len(w)-1]=='!' or w[len(w)-1]=='?':
            ans+=1
        elif(w=="."):
            ans+=1
        elif len(w)>1:
            if w[len(w)-1]=='.' and w[len(w)-2]!='.':
                ans+=1 
    return ans
            
    
def main():

    L=list(map(str,input().split()))
    
    result = SentenceCount(L);
    print(result)
if __name__ == "__main__":
    main()
JOB ALERT ON INSTAGRAM FOLLOW NOW>>
JOB ALERT ON YOUR EMAIL DAILY SUBSCRIBE NOW>>

Follow regularly our Dailyrecruitment.in site to get upcoming all up-to-date information.

Govt Jobs by Qualifications

Education & Vacancies Salary Apply Link
10th Pass Govt Jobs - 5,000 Vacancies Rs. 5,200 - 63,200 Apply Now
12th Pass Govt Jobs - 18,000+ Vacancies Rs. 5,200 - 92,300 Apply Now
ITI Pass Jobs - 3,500 Vacancies Rs. 5,200 - 35,000 Apply Now
Any Graduate Jobs - 19,100 Vacancies Rs. 5,200 - 92,300 Apply Now
Central Govt Jobs Rs. 5,200 - 17,000 Apply Now
Bank Jobs - 1,000 Vacancies Rs. 5,200 - 29,200 Apply Now
Diploma Jobs - 9,300 Vacancies Rs. 5,200 - 35,000 Apply Now
BTech/BE Jobs - 18,000 Vacancies Rs. 15,000 - 1,00,000 Apply Now
Data Entry Jobs - 1,300 Vacancies Rs. 5,200 - 29,200 Apply Now
Private Jobs Rs. 10,000 - 67,700 Apply Now