• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Strings, Arrays & Hash Tables — Let’s Talk About the One You’re Probably Not Using Enough

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
If you’ve been coding for a bit, chances are you're already comfortable working with strings and arrays.
You loop through them, slice them, search them, sort them — all good.

So let’s skip the warm-up and jump straight into the one structure that quietly powers a ton of efficient solutions but often doesn’t get the spotlight it deserves:

? Hash Tables (a.k.a. Hash Maps, Dictionaries)


Hash Tables are data structures that store key-value pairs, and they give you constant-time lookups on average — O(1) time complexity for accessing, inserting, and deleting items.

? Why They Matter


Hash Tables are your go-to when you need to:

  • Count things (like frequencies of characters or items)
  • Track what you’ve seen (e.g., duplicates)
  • Map one thing to another (like IDs to objects)

They're elegant, fast, and can simplify problems that otherwise require nested loops.

? Real-World Analogy


Imagine a real-world dictionary:

  • You want to look up the word “banana”
  • You flip straight to the page and find the definition No scanning every word — just direct access.

That’s what a hash table gives you: instant access via a key.

? Example: Find the First Duplicate


Let’s say you’re given this array:


const nums = [2, 5, 1, 2, 3, 5, 1];

You want to return the first number that appears more than once.
In this case, the answer should be 2, because it's the first value that repeats.

? How would we normally solve it?


A naive way might be to use two loops to compare every element with every other one:


// O(n^2) brute force
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums === nums[j]) {
return nums;
}
}
}

But this is inefficient — it checks every possible pair and takes O(n²) time.

⚡ Now, let’s use a Hash Table (Set) for an efficient solution


We can use a Set to store the values we’ve already seen.
As we iterate through the array:

  • If we haven’t seen the number before, we add it to the set.
  • If we’ve already seen it, we return it immediately — that’s our duplicate.

function findFirstDuplicate(nums) {
const seen = new Set();

for (let num of nums) {
if (seen.has(num)) {
return num; // ? Found the first duplicate!
}
seen.add(num);
}

return -1; // No duplicates found
}

This solution is:

  • ✅ O(n) time — we loop through the array once
  • ✅ O(n) space — for the Set
  • ✅ Much easier to understand and maintain
✅ Why this works

  • Set is like a quick-access notepad. You ask: “Have I seen this number before?”
  • Because lookups in a set are constant time, it’s super fast even with big arrays.

This pattern — using a hash table to track what you've seen — shows up all the time in real-world problems.

⚡ TL;DR


You already know strings and arrays — but hash tables are where things start getting really efficient.

If you're learning data structures and algorithms, make sure hash tables are part of your everyday problem-solving toolkit.

They’re your cheat code for clean, scalable code.

That’s it for today!
Hope this helped you see hash tables in a new light.
Happy coding! ?


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу