Skip to content

Commit

Permalink
combine arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
brendonmiranda committed Nov 21, 2024
1 parent 7e7bc3a commit c355ea2
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions src/main/java/squarespace/CombineArrays.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package squarespace;

public class CombineArrays {

public static void main(String... args) {
var arr = combineArrays(new int[]{1, 3, 5}, new int[]{2, 4, 6});
for (int i : arr) {
System.out.println(i);
}
}

public static int[] combineArrays(int[] a, int[] b) {

// In:
// [1, 3, 5]
// [2, 4, 6]
//
// Out:
// [1,2,3,4,5,6]
final int aSize = a.length;
final int bSize = b.length;

final int[] res = new int[aSize + bSize];

int i = 0;
int aIndex = 0;
int bIndex = 0;


while (i < aSize + bSize) {

boolean aReached = aIndex == aSize; // f
boolean bReached = bIndex == bSize; // f
if (!aReached && !bReached) {
int av = a[aIndex]; // a
int bv = b[bIndex]; // 1 = 1

if (av < bv) {
res[i] = av;
aIndex++;
} else {
res[i] = bv;
bIndex++;
}
i++; // 4
continue;
}

if (!aReached) {
res[i] = a[aIndex];
aIndex++;
}

if (!bReached) {
res[i] = b[bIndex];
bIndex++;
}

i++;
}


return res;

// o(n) in which n = aSize + bSize

}

}

0 comments on commit c355ea2

Please sign in to comment.