For example, given A = [1, 2, 1, 1]
, the function should return 3.
Creates only three different sequences: (1, 2, 1), (1, 1, 1) and (2, 1, 1)
. The correct answer for this example is 3.
Given
A = [1, 2, 3, 4]
, the function should return 4. There are four ways:(1, 2, 3), (1, 2, 4), (1, 3, 4) and (2, 3, 4)
.Given
A = [2, 2, 2, 2]
, the function should return 1. There is only one way:(2, 2, 2)
.Given
A = [2, 2, 1, 2, 2]
, the function should return 4. There are four ways:(1, 2, 2), (2, 1, 2), (2, 2, 1) and (2, 2, 2)
.Given
A = [1, 2]
, the function should return 0
Write an efficient algorithm for the following assumptions:
N is an integer within the range [0..100,000]; each element of array A is an integer within the range [1..N].
Here is my Brute Force Solution below!
I was wondering if anybody out there has a better more optimized solution?
Detected time complexity of this solution:
O(N**3*log(N)) or O(N**4)
const theatreTickets = (array) => {
let combos = []
if(array.length < 2) {
combos.length = 0
}
for(let i = 0; i <= array.length; i++) {
for(let j = i + 1; j <= array.length - 1; j++) {
for(let k = j + 1; k <= array.length - 1; k++) {
combos.push([array[i], array[j], array[k]])
}
}
}
combos = Array.from(new Set(combos.map(JSON.stringify)), JSON.parse)
return combos.length
}
console.log(theatreTickets([1, 2, 1, 1])) // Should Be 3
Thank you!