IBM Coding Questions With Solutions 2024 (Python/Java/C/C++) | IBM MCQ Coding Questions For Freshers

IBM Coding Questions With Solutions 2024 | IBM Coding Questions and Answers | IBM Previous Year Coding Questions | IBM Coding Questions For Freshers | IBM Model Coding Questions & Answers PDF

IBM Coding Questions With Solutions 2024: All of the fundamental algorithms, data structures, and programming concepts are included in the IBM Coding Questions. If you’re interested in working at IBM and don’t know how to prepare for the questions in the IBM Coding Round, we can help. The coding round is one of the most crucial parts of the IBM test. In this article, we covered a variety of sample IBM Coding rounds and potential solutions. We will talk about IBM Coding Questions in this article.

A unique technique for assessing a candidate’s capacity for problem-solving is offered by IBM. On their blog, they frequently hold coding competitions. Should you successfully finish the challenge, you might receive an interview request. This tutorial will teach you all there is to know about IBM. More details like IBM Coding Questions and Answers, IBM Coding Questions and Answers, IBM Interview Questions and Answers, IBM Cut Off, Salary, Hike, Increment, Annual Appraisal, etc. are available on this page

IBM Coding Questions With Solutions For Freshers

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: 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)

IBM Coding Questions With Solutions For Java

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: 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: 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);
	}
}
JOB ALERT ON INSTAGRAM FOLLOW NOW>>
JOB ALERT ON YOUR EMAIL DAILY SUBSCRIBE NOW>>

Keep an eye on Dailyrecruitment.in for the most up-to-date information about upcoming exams and results. Find out about official notices, Exam Patterns, Syllabus, Previous Question Papers, Expected Cut Off, Results, Merit List, Study Materials, and much more. Now is the time to bookmark in order to take advantage of even more amazing career opportunities.

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