Skip to content

Commit

Permalink
[Hacker Rank] Interview Preparation Kit: Hash Tables: Ice Cream Parlo…
Browse files Browse the repository at this point in the history
…r. Optimized solution ✅.
  • Loading branch information
Gonzalo Diaz committed Aug 16, 2024
1 parent 7635809 commit 746ab0c
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
{
"costs": [1, 4, 5, 3, 2],
"money": 90,
"expected": null
"expected": []
}
]
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,46 @@
* @link Problem definition [[docs/hackerrank/interview_preparation_kit/search/ctci-ice-cream-parlor.md]]
*/

export function whatFlavorsCompute(
cost: number[],
money: number
): number[] | null {
const cache: Record<number, number> = {};

for (const [key, price] of Object.entries(cost)) {
const i = parseInt(key);
const diff = money - price;
const cacheKeys = new Set(Object.keys(cache));

if (cacheKeys.has(diff.toString())) {
return [i + 1, cache[diff] + 1].sort((a, b) => a - b);
export function whatFlavorsCompute(cost: number[], money: number): number[] {
let ans1;
let ans2;

const CACHE: Record<number, number> = {};

for (const price of cost) {
CACHE[price] = Number.isInteger(CACHE[price]) ? CACHE[price] + 1 : 1;
}

for (const i in cost) {
const v1 = cost[i];
const v2 = money - v1;

if (v1 != v2) {
if (CACHE?.[v1] && CACHE?.[v2]) {
ans1 = v1;
ans2 = v2;
break;
}
} else {
// count of the element must be greater than 1 if they are same
if (CACHE?.[v1] && CACHE[v1] > 1) {
ans1 = v1;
ans2 = v1;
break;
}
}
}

cache[price] = i;
const result: number[] = [];
for (const i in cost) {
const x: number = parseInt(i);

if (cost[x] == ans1 || cost[x] == ans2) {
result.push(x + 1);
}
}

return null;
return result;
}

export function whatFlavors(cost: number[], money: number): void {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
export function what_flavors_bruteforce_compute(
cost: number[],
money: number
): number[] | null {
): number[] {
for (const _i in cost) {
const i: number = parseInt(_i);
const x: number = cost[i];
Expand All @@ -20,7 +20,7 @@ export function what_flavors_bruteforce_compute(
}
}

return null;
return [];
}

export function whatFlavors(cost: number[], money: number): void {
Expand Down

0 comments on commit 746ab0c

Please sign in to comment.