Skip to content

Instantly share code, notes, and snippets.

@youssef3wi
Created January 21, 2024 17:01
Show Gist options
  • Select an option

  • Save youssef3wi/9ac9d4fc4d45b7cc3d2effee9fbdd0fa to your computer and use it in GitHub Desktop.

Select an option

Save youssef3wi/9ac9d4fc4d45b7cc3d2effee9fbdd0fa to your computer and use it in GitHub Desktop.
A storage room full of boxes.
import java.util.Scanner;
/**
* You are in a storage room full of boxes. We want to make some room by moving the empty boxes to the end of the room and not moving the other side.
* Given an integer array containing the weights of the boxes, write a function to moves all the empty boxes to the end of the room.
* <p/>
* <b>INPUT: </b>
* <b>Line1: The N weights</b>
* <p/>
* <b>OUTPUT:</b>
* The new state of the room after moving all the empty boxes
* <p/>
* <b>CONSTRAINTS:</b>
* 0 < N < 100000
* <p/>
* <b>EXAMPLE:</b>
* <table>
* <tr>
* <td>Input</td> <td>Output</td>
* </tr>
* <tr>
* <td>5</td> <td>1 3 12 0 0</td>
* </tr>
* <tr>
* <td>0 1 0 3 12</td>
* </tr>
* </table>
*/
public class Boxes {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] boxes = new int[n];
for (int i = 0; i < n; i++) {
int weight = in.nextInt();
boxes[i] = weight;
}
for (int idx = 0; idx < n; idx++) {
if (boxes[idx] == 0) {
for (int jdx = idx + 1; jdx < n; jdx++) {
if (boxes[jdx] != 0) { // first non-zero
boxes[idx] = boxes[jdx];
boxes[jdx] = 0;
break;
}
}
}
}
StringBuilder result = new StringBuilder();
for (int box : boxes) {
result.append(box).append(" ");
}
System.out.println(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment