# O(1) - Constant Time

> Same speed whether your dataset has 1 item or 1 billion. The holy grail.

- **Category**: Big O
- **Subcategory**: complexity
- **Canonical URL**: https://designpattern.fyi/big_o/constant-time/

---

## Description
Clean, reusable architecture pattern.


## Use Cases
Cache lookup — checking if a key exists in a Redis cache or a JavaScript Map. No matter if the cache has 10 or 10 million entries, the lookup takes the same time. Every LRU cache, routing table, and session store is built on this.



## Implementation Example

```javascript
// O(1) — Array index access
function getElement(arr, i) {
  return arr[i]; // Direct memory address calculation — always O(1)
}

// O(1) — Hash map lookup
const cache = new Map();
cache.set('user:123', { name: 'Alice', role: 'admin' });
const user = cache.get('user:123'); // O(1) average case — no traversal

// O(1) — Stack push/pop
const stack = [];
stack.push(42);   // O(1) — append to end
stack.pop();      // O(1) — remove from end
const top = stack[stack.length - 1]; // O(1) — peek without removal

// O(1) — Lookup table (precomputed)
const DAY_NAMES = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
const getDayName = (n) => DAY_NAMES[n % 7]; // O(1) — direct index

```



## Trade-offs


### Advantages

- Performance is completely predictable — no surprises under load

- Scales perfectly — adding more data never slows the operation

- Ideal for hot paths, real-time systems, and latency-sensitive code

- Foundation of efficient data structures (hash maps, arrays, stacks)




### Considerations & Drawbacks

- Not achievable for problems that inherently require examining multiple elements

- Hash map O(1) is average case — worst case is O(n) on hash collisions (use good hash functions)

- Sometimes requires O(n) preprocessing or extra memory to enable O(1) access later

- Can create a false sense of security — O(1) with a large constant can still be slow







---
**Reference**: [Original Source](https://www.bigocheatsheet.com)

