HackerRank Cut the sticks Solution

Hello Programmers, In this post, you will know how to solve the HackerRank Cut the sticks Solution. This problem is a part of the HackerRank Algorithms Series.

HackerRank Cut the sticks Solution
HackerRank Cut the sticks Solution

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

HackerRank Cut the sticks Solution

Task

You are given a number of sticks of varying lengths. You will iteratively cut the sticks into smaller sticks, discarding the shortest pieces until there are none left. At each iteration you will determine the length of the shortest stick remaining, cut that length from each of the longer sticks and then discard all the pieces of that shortest length. When all the remaining sticks are the same length, they cannot be shortened so discard them.

Given the lengths of n sticks, print the number of sticks that are left before each iteration until there are none left.

Example
arr = [1, 2, 3]

The shortest stick length is 1, so cut that length from the longer two and discard the pieces of length 1. Now the lengths are arr = [1, 2]. Again, the shortest stick is of length 1, so cut that amount from the longer stick and discard those pieces. There is only one stick left, arr = [1], so discard that stick. The number of sticks at each iteration are answer = [3, 2, 1].

Function Description

Complete the cutTheSticks function in the editor below. It should return an array of integers representing the number of sticks before each cut operation is performed.

cutTheSticks has the following parameter(s):

  • int arr[n]: the lengths of each stick

Returns

  • int[]: the number of sticks after each iteration

Input Format

The first line contains a single integer n, the size of arr.
The next line contains n space-separated integers, each an arr[i], where each value represents the length of the ith stick.

Constraints

  • 1 <= n <= 1000
  • 1 <= arr[i] <= 1000

Sample Input 0

STDIN Function
—– ——–
6 arr[] size n = 6
5 4 4 2 2 8 arr = [5, 4, 4, 2, 2, 8]

Sample Output 0

6
4
2
1

Explanation 0

sticks-length        length-of-cut   sticks-cut
5 4 4 2 2 8             2               6
3 2 2 _ _ 6             2               4
1 _ _ _ _ 4             1               2
_ _ _ _ _ 3             3               1
_ _ _ _ _ _           DONE            DONE

Sample Input 1

8
1 2 3 4 3 3 2 1

Sample Output 1

8
6
4
1

Explanation 1

sticks-length         length-of-cut   sticks-cut
1 2 3 4 3 3 2 1         1               8
_ 1 2 3 2 2 1 _         1               6
_ _ 1 2 1 1 _ _         1               4
_ _ _ 1 _ _ _ _         1               1
_ _ _ _ _ _ _ _       DONE            DONE

HackerRank Cut the sticks Solution

Cut the sticks Solution in C

#include<stdio.h>
int main()
{
	int n;
	scanf("%d",&n);
	int a[1002]={0};
	int i;
	for(i=0;i<n;i++)
	{
		int c;
		scanf("%d",&c);
		a[c]++;
	}
	int t=n;
	for(i=0;i<1001;i++)
	{
		if(a[i]>0)
		{
			printf("%d\n",t);
			t=t-a[i];
		}
	}
	return  0;
}

Cut the sticks Solution in Cpp

#include <iostream>
#include <stdio.h>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <cassert>
#include <algorithm>
#define Pi 3.14159
typedef long long int ll;
using namespace std;
int main ()
{
    int n;
    cin >> n;
    int a[n];
    int b[1001]={0};
    for (int i = 0 ; i<n;i++){cin >>a[i];b[a[i]] ++;}
    cout<<n<<endl;
    for (int i = 1; i <= 1000; i++){n-=b[i];if(b[i] && n)cout<<n<<endl;}
}

Cut the sticks Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
	public static void main(String[] args) {
		Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in), 128 << 10));
		int n = in.nextInt();
		int[] counts = new int[1001];
		for (int i = 0; i < n; i++) counts[in.nextInt()]++;
		for (int i = 0; i <= 1000; i++) {
			if (counts[i] > 0) {
				System.out.println(n);
				n -= counts[i];
			}
		}
	}
}

Cut the sticks Solution in Python

#!/usr/bin/env python
import collections, sys
if __name__ == '__main__':
    N = int(sys.stdin.readline())
    a = sorted(map(int, sys.stdin.readline().split()))
    
    c = collections.Counter(a)
    count = [c[k] for k in sorted(c)]
    
    for i in range(len(count)):
    	print(sum(count[i:]))

Cut the sticks Solution using JavaScript

'use strict';
function processData(input) {
    var parse_fun = function (s) { return parseInt(s, 10); };
    var lines = input.split('\n');
    var N = parse_fun(lines.shift());
    var data = lines[0].split(' ').splice(0, N).map(parse_fun);
    data.sort(function (n1, n2) { return n1 - n2; });
    var res = [];
    while (data.length > 0) {
        res.push(data.length);
        var min = data[0];
        data = data.map(function (n) { return n - min; });
        data = data.filter(function (n) {return n > 0; });
    }
    console.log(res.join('\n'));
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
var _input = "";
process.stdin.on("data", function (input) { _input += input; });
process.stdin.on("end", function () { processData(_input); });

Cut the sticks Solution in Scala

object Solution {
    def main(args: Array[String]) {
      val n = readLine.trim.toInt
      if (n < 1 || n > 1000) println("Invalid value for N")
      else {
        val xs = readLine.trim.split(" ").map(_.trim.toInt).toList
        if (xs.length != n) println("Invalid number of items")
        else {
          val ls = cutTheSticks(xs, Nil)
          ls.foreach(println)
        }
      }
    }
  
  def cutTheSticks(xs: List[Int], ls: List[Int]): List[Int] = xs match {
    case Nil => ls.reverse
    case h :: t => 
      val cutLen = xs.min
      val xs1 = xs.map(_ - cutLen)
      cutTheSticks(xs1.filter(_ > 0), xs.length :: ls)
  }
}

Cut the sticks Solution in Pascal

(* Enter your code here. Read input from STDIN. Print output to STDOUT *)
program cut;
var
    test : integer;
    length : array[1..1000] of integer;
    short : integer;
    count : integer;
    cutted : integer;
    i,j : integer;
begin
    readln(test);
    cutted := test;
    for i := 1 to test do
        read(length[i]);
    for i := 1 to 1000 do
    begin
        count := 0;
        for j := 1 to test do
        begin
            if length[j]=i then
            begin
                count := count+1;
            end;
        end;
        if count <> 0 then
        begin
            writeln(cutted);
            cutted := cutted - count;
        end;
    end;
end.
     

Disclaimer: This problem (Cut the sticks) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: HackerRank Append and Delete Solution

Leave a Reply

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