Question #127MediumGeneral

Learn Data Structure and Algorithm ?

Answer

Overview

Data Structures and Algorithms (DSA) are the foundation of efficient software. Understanding them is essential for coding interviews and building performant applications.


Core Data Structures

1. Array / List

dart
// O(1) access by index, O(n) search
final list = [1, 2, 3, 4, 5];
list.add(6);           // O(1) amortized
list.insert(0, 0);     // O(n) — shifts elements
list.removeAt(2);      // O(n)
list[0];               // O(1) access

2. Map (HashMap)

dart
// O(1) average for get/put
final map = <String, int>{};
map['apple'] = 5;      // O(1)
map['apple'];          // O(1)
map.containsKey('a');  // O(1)

3. Set

dart
// O(1) average for add/contains — unique elements
final set = <int>{1, 2, 3};
set.add(2);            // No duplicate — still {1, 2, 3}
set.contains(2);       // O(1)

4. Stack

dart
// LIFO — Last In First Out
final stack = <int>[];
stack.add(1);          // push
stack.add(2);
final top = stack.removeLast(); // pop — O(1)

5. Queue

dart
import 'dart:collection';
// FIFO — First In First Out
final queue = Queue<int>();
queue.addLast(1);      // enqueue — O(1)
queue.removeFirst();   // dequeue — O(1)

6. Linked List

dart
// O(1) insert/delete at known node, O(n) search
// Dart doesn't have built-in — use Queue or implement custom

Core Algorithms

Sorting

dart
// Built-in sort — O(n log n)
final list = [5, 2, 8, 1, 9];
list.sort();           // [1, 2, 5, 8, 9]
list.sort((a, b) => b.compareTo(a)); // Descending

// Dart also has: list.sort() using TimSort internally

Binary Search — O(log n)

dart
// Find target in sorted list
int binarySearch(List<int> sorted, int target) {
  int left = 0, right = sorted.length - 1;
  while (left <= right) {
    int mid = (left + right) ~/ 2;
    if (sorted[mid] == target) return mid;
    if (sorted[mid] < target) left = mid + 1;
    else right = mid - 1;
  }
  return -1;
}

Two Pointer — O(n)

dart
// Check if array has pair summing to target
bool hasPairSum(List<int> sorted, int target) {
  int left = 0, right = sorted.length - 1;
  while (left < right) {
    final sum = sorted[left] + sorted[right];
    if (sum == target) return true;
    if (sum < target) left++;
    else right--;
  }
  return false;
}

Big-O Cheat Sheet

OperationArrayHashMapSet
AccessO(1)O(1)
SearchO(n)O(1)O(1)
InsertO(n)O(1)O(1)
DeleteO(n)O(1)O(1)

Learning Resources

ResourceType
LeetCodePractice problems
NeetCode.ioStructured DSA roadmap
"Grokking Algorithms" bookBeginner-friendly visual book
CS50 (Harvard)Free comprehensive course
HackerRankStructured challenges

Flutter Dev Focus: For interviews, focus on: arrays, hashmaps, strings, recursion, and BFS/DFS on trees/graphs. For app performance, focus on choosing the right data structure (List vs Set vs Map) based on access patterns.