Tantangan algoritma standar wawancara FAANG/MNC: Mencari dua angka di dalam array yang jika dijumlahkan menghasilkan nilai target tertentu.
Poin Kunci Materi:
- Brute Force O(n^2): Menggunakan nested loop ganda yang lambat untuk kumpulan data besar.
- Optimasi Hash Map O(n): Menggunakan
std::unordered_map untuk mencari komplementer target dalam waktu konstan. - Structured Binding: Membongkar nilai kembalian pair dengan sintaks modern C++17
auto [idx1, idx2].
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {
font-family: 'Fira Code', Consolas, Monaco, monospace;
background: #0f172a;
color: #f8fafc;
padding: 20px;
margin: 0;
line-height: 1.6;
}
.header {
background: #1e293b;
padding: 10px 16px;
border-radius: 8px 8px 0 0;
border-bottom: 2px solid #334155;
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
color: #94a3b8;
}
.dot { width: 12px; height: 12px; border-radius: 50%; display: inline-block; }
.dot-red { background: #ef4444; }
.dot-yellow { background: #eab308; }
.dot-green { background: #22c55e; }
.code-box {
background: #1e293b;
padding: 18px 20px;
border-bottom: 1px dashed #334155;
color: #38bdf8;
font-size: 14px;
white-space: pre-wrap;
}
.comment { color: #64748b; font-style: italic; }
.output-box {
background: #020617;
padding: 18px 20px;
border-radius: 0 0 8px 8px;
color: #e2e8f0;
font-size: 13px;
}
</style>
</head>
<body>
<div class="header">
<span class="dot dot-red"></span>
<span class="dot dot-yellow"></span>
<span class="dot dot-green"></span>
<span style="margin-left: 8px; font-weight: bold; color: #38bdf8;">⚙️ C++ Code Challenges - Skillance C++20</span>
</div>
<div class="code-box">
<span class="comment">// Skrip C++20 - Skillance Academy Indonesia</span>
#include <iostream>
#include <vector>
#include <unordered_map>
// Problem: Two Sum O(n)
std::pair<int, int> twoSum(const std::vector<int>& nums, int target) {
std::unordered_map<int, int> mapAngka;
for (int i = 0; i < (int)nums.size(); ++i) {
int sisa = target - nums[i];
if (mapAngka.count(sisa)) {
return {mapAngka[sisa], i};
}
mapAngka[nums[i]] = i;
}
return {-1, -1};
}
int main() {
std::vector<int> angka = {2, 7, 11, 15};
int target = 9;
auto [idx1, idx2] = twoSum(angka, target);
std::cout << "Two Sum Solusi Hash Map:\n";
std::cout << "Target: " << target << " ditemukan di indeks: [" << idx1 << ", " << idx2 << "]\n";
return 0;
}
</div>
<div class="output-box">
<div style="color: #64748b; margin-bottom: 6px;">[Terminal Output] > g++ -std=c++20 main.cpp -o main && ./main</div>
<div style="color: #4ade80; font-weight: bold;">Two Sum Solusi Hash Map:<br>Target: 9 ditemukan di indeks: [0, 1]</div>
</div>
</body>
</html>
Coba Sendiri (Try it Yourself) »