Skip to content
Programmingoneonone
Programmingoneonone
  • Engineering Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
    • 100+ C++ Programs
  • Solutions
    • HackerRank
      • Algorithms Solutions
      • C solutions
      • C++ solutions
      • Java solutions
      • Python solutions
    • Leetcode Solutions
    • HackerEarth Solutions
  • Work with US
Programmingoneonone
Programmingoneonone

HackerRank Organizing Containers of Balls problem solution

YASH PAL, 31 July 20241 December 2025

In this HackerRank Organizing Containers of Balls problem solution, You must perform q queries where each query is in the form of a matrix, M. For each query, print Possible on a new line if David can satisfy the conditions above for the given matrix. Otherwise, print Impossible.

David has several containers, each with a number of balls in it. He has just enough containers to sort each type of ball he has into its own container. David wants to sort the balls using his sort method.

David wants to perform some number of swap operations such that:

  • Each container contains only balls of the same type.
  • No two balls of the same type are located in different containers.
HackerRank Organizing Containers of Balls problem solution

Hackerrank Organizing containers of balls problem solution in Python programming.

#!/bin/python3

import sys


q = int(input().strip())
for a0 in range(q):
    n = int(input().strip())
    M = []
    for M_i in range(n):
       M_t = [int(M_temp) for M_temp in input().strip().split(' ')]
       M.append(M_t)
    # your code goes here

    Rows = []
    Cols = []
    Works = True
    
    for i in range(n):
        Rows.append(sum(M[i]))
       
            
    N = [list(i) for i in zip(*M)]     
    for i in range(n):
        Cols.append(sum(N[i]))
  
    Rows.sort()
    Cols.sort()
    if(Rows == Cols):
        print("Possible")
    else:
        print("Impossible")

Organizing containers of balls problem solution in Java Programming.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    
    private static boolean greedy(final int[] types, final int[] containers) {
        final int n = types.length;
        for (int i = n - 1; i >= 0; i--) {
            if (types[i] > containers[i]) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int q = in.nextInt();
        for(int a0 = 0; a0 < q; a0++){
            int n = in.nextInt();
            int[][] M = new int[n][n];
            for(int M_i=0; M_i < n; M_i++){
                for(int M_j=0; M_j < n; M_j++){
                    M[M_i][M_j] = in.nextInt();
                }
            }
            final int[] types = new int[n];
            for (int t = 0; t < n; t++) {
                for (int i = 0; i < n; i++) {
                    types[t] += M[i][t];
                }
            }
            
            final int[] containers = new int[n];
            for (int c = 0; c < n; c++) {
                for (int i = 0; i < n; i++) {
                    containers[c] += M[c][i];
                }
            }
            
            Arrays.sort(types);
            Arrays.sort(containers);
            final boolean possible = greedy(types, containers);
            final String answer = possible ? "Possible" : "Impossible";
            System.out.println(answer);
        }
    }
}

Problem solution in C++ programming.

#define _CRT_SECURE_NO_WARNINGS
#pragma comment(linker, "/stack:16777216")
#include <string>
#include <vector>
#include <map>
#include <list>
#include <iterator>
#include <set>
#include <queue>
#include <iostream>
#include <sstream>
#include <stack>
#include <deque>
#include <cmath>
#include <memory.h>
#include <cstdlib>
#include <cstdio>
#include <cctype>
#include <algorithm>
#include <utility>
#include <assert.h>
#include <time.h>
#include <complex.h>


#include <fstream>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

#define FOR(i, a, b) for(int i=(a);i<(b);i++)
#define RFOR(i, b, a) for(int i=(b)-1;i>=(a);--i)
#define FILL(A,value) memset(A,value,sizeof(A))
#define ALL(V) V.begin(), V.end()
#define SZ(V) (int)V.size()
#define PB push_back
#define MP make_pair
#define Pi 3.14159265358979

typedef long long Int;
typedef unsigned long long UInt;
typedef vector<int> VI;
typedef pair<Int, Int> PII;

const int INF = 1000000000;
const int MAX = 300007;
const int MAXD = 20;
const int MOD = 1000000007;

int A[MAX];
int B[MAX];

int main()
{
    //freopen("in.txt" , "r" , stdin);
    //freopen("out.txt" , "w" , stdout);
    
    int q;
    cin >> q;
    FOR(qq,0,q)
    {
        int n;
    cin >> n;
    FILL(A, 0);
    FILL(B,0);
    FOR(i,0,n)
        FOR(j,0,n)
        {
            int x;
            cin >> x;
            A[i] += x;
            B[j] += x;
        }
        sort(A , A + n);
        sort(B , B + n);
        bool ok = 1;
        FOR(i,0,n)
            ok &= (A[i] == B[i]);
        if (ok) cout << "Possible"<< endl;
        else cout << "Impossible" << endl;
    }
    
    
    return 0;
}

Problem solution in C programming.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int q; 
    scanf("%d",&q);
    for(int a = 0; a < q; a++){
        int n,f=0,d=0; 
        scanf("%d",&n);
        int M[n][n],x[n],s,y=0,z[n],l;
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++)
            scanf("%d ",&M[i][j]);
       
        }
       for(int i=0;i<n;i++){ 
           s=0;
           l=0;
            for(int j=0;j<n;j++)
                     s=s+M[j][i];                               
                  x[i]=s;      
           for(int j=0;j<n;j++)
                     l=l+M[i][j];       
               z[i]=l; 
       }
        for(int i=0;i<n;i++) {
            d=0;
              for(int j=0;j<n;j++)
                if(x[i]==z[j]) d=1;
                  
                 f=f+d;   
        }
        if(f==n && d==1) printf("Possiblen");
        else printf("Impossiblen");
        
        
    }
    return 0;
}

Problem solution in JavaScript programming.

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function main() {
    var q = parseInt(readLine());
    for(var a0 = 0; a0 < q; a0++){
        var n = parseInt(readLine());
        var M = [];
        for(M_i = 0; M_i < n; M_i++){
           M[M_i] = readLine().split(' ');
           M[M_i] = M[M_i].map(Number);
        }
        
        // your code goes here
        var containerMap = {};
        var itemMap = {};
        for (var i = 0; i < M.length; i++) {
            var containerCount = 0;
            itemCounts = M[i];
            for (var j = 0; j < itemCounts.length; j++) {
                var itemCount = itemCounts[j];
                containerCount += itemCount;
                if (!itemMap[j]) itemMap[j] = 0;
                itemMap[j] += itemCount;
            }
            if (!containerMap[containerCount]) containerMap[containerCount] = 0;
            containerMap[containerCount]++;
        }
        
        var possible = true;
        for (var key in itemMap) {
            var count = itemMap[key];
            if (!containerMap[count]) {
                possible = false;
                break;
            }
            containerMap[count]--;
        }
        
        if (possible) {
            console.log('Possible');
        } else {
            console.log('Impossible');
        }
    }
}

Algorithms coding problems solutions AlgorithmsHackerRank

Post navigation

Previous post
Next post

Leave a Reply

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

Programmingoneonone

We at Programmingoneonone, also known as Programming101 is a learning hub of programming and other related stuff. We provide free learning tutorials/articles related to programming and other technical stuff to people who are eager to learn about it.

Pages

  • About US
  • Contact US
  • Privacy Policy

Practice

  • Java
  • C++
  • C

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes