Code Snippets Gallery
Bubble Sort Implementation
A simple implementation of the bubble sort algorithm with detailed comments
def bubble_sort(arr):
"""
Sorts an array using the bubble sort algorithm.
Time Complexity: O(n²)
Space Complexity: O(1)
"""
n = len(arr)
for i in range(n):
# Flag to optimize for already sorted arrays
swapped = False
# Last i elements are already in place
for j in range(0, n - i - 1):
# Compare adjacent elements
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
# If no swapping occurred, array is already sorted
if not swapped:
break
return arr
sortingalgorithmbeginnerarraytutorialinterview
Amitava Dattapython
Quick Sort Implementation
An efficient implementation of the quick sort algorithm
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
sortingalgorithm
Pranay Depython
Merge Sort Implementation
A stable, efficient implementation of the merge sort algorithm
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
sortingalgorithm
Amitava Dattapython
Linked List Implementation
A complete implementation of a singly linked list with common operations
class ListNode<T> {
val: T;
next: ListNode<T> | null;
constructor(val: T) {
this.val = val;
this.next = null;
}
}
class LinkedList<T> {
head: ListNode<T> | null;
constructor() {
this.head = null;
}
append(val: T): void {
const newNode = new ListNode(val);
if (!this.head) {
this.head = newNode;
return;
}
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
delete(val: T): void {
if (!this.head) return;
if (this.head.val === val) {
this.head = this.head.next;
return;
}
let current = this.head;
while (current.next) {
if (current.next.val === val) {
current.next = current.next.next;
return;
}
current = current.next;
}
}
print(): void {
let current = this.head;
const values: T[] = [];
while (current) {
values.push(current.val);
current = current.next;
}
console.log(values.join(' -> '));
}
}
linked-listdata-structureintermediateinterview
Pranay Detypescript
Binary Search Implementation
Efficient binary search algorithm for sorted arrays
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
searchingalgorithmarrayinterviewbeginner
Amitava Dattajavascript
Fibonacci Sequence
Generate Fibonacci sequence using Python
def fibonacci(n: int) -> list[int]:
"""Generate Fibonacci sequence up to n numbers."""
sequence = [0, 1]
while len(sequence) < n:
sequence.append(sequence[-1] + sequence[-2])
return sequence
def main():
n = 10
result = fibonacci(n)
print(f"First {n} Fibonacci numbers: {result}")
if __name__ == "__main__":
main()
mathbeginnertutorialexample
Amitava Dattapython
Async Error Handler
Utility function for handling async/await errors in Express
const asyncHandler = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next))
.catch((error) => {
console.error('Error:', error);
res.status(500).json({
success: false,
message: 'Internal server error',
error: process.env.NODE_ENV === 'development' ? error.message : undefined
});
});
};
// Example usage
app.get('/api/users', asyncHandler(async (req, res) => {
const users = await User.find({});
res.json({ success: true, data: users });
}));
webutilityerror-handlingintermediate
Pranay Dejavascript
Generic Cache Implementation
Type-safe caching utility using TypeScript generics
class Cache<T> {
private cache: Map<string, { data: T; timestamp: number }>;
private ttl: number;
constructor(ttlSeconds: number = 3600) {
this.cache = new Map();
this.ttl = ttlSeconds * 1000;
}
set(key: string, value: T): void {
this.cache.set(key, {
data: value,
timestamp: Date.now(),
});
}
get(key: string): T | null {
const item = this.cache.get(key);
if (!item) return null;
const isExpired = Date.now() - item.timestamp > this.ttl;
if (isExpired) {
this.cache.delete(key);
return null;
}
return item.data;
}
clear(): void {
this.cache.clear();
}
}
// Example usage
const userCache = new Cache<User>();
userCache.set('user1', { id: 1, name: 'John' });
utilityadvanceddata-structure
Amitava Dattatypescript
Binary Tree Implementation
Complete binary tree implementation in Java with basic operations
public class BinaryTree<T> {
private class Node {
T data;
Node left;
Node right;
Node(T data) {
this.data = data;
left = right = null;
}
}
private Node root;
public void insert(T data) {
root = insertRec(root, data);
}
private Node insertRec(Node root, T data) {
if (root == null) {
root = new Node(data);
return root;
}
if (Math.random() < 0.5)
root.left = insertRec(root.left, data);
else
root.right = insertRec(root.right, data);
return root;
}
public void inorderTraversal() {
inorderRec(root);
}
private void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.print(root.data + " ");
inorderRec(root.right);
}
}
}
data-structuretreebinary-treeintermediate
Pranay Dejava
QuickSort Implementation
Efficient QuickSort algorithm implementation in C++
template<typename T>
void quickSort(T arr[], int low, int high) {
if (low < high) {
// Partition the array
T pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
std::swap(arr[i], arr[j]);
}
}
std::swap(arr[i + 1], arr[high]);
int pi = i + 1;
// Recursively sort sub-arrays
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
// Example usage
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
std::cout << "Sorted array: ";
for (int i = 0; i < n; i++)
std::cout << arr[i] << " ";
return 0;
}
sortingalgorithmadvanced
LINQ Query Examples
Common LINQ query patterns in C#
public class LinqExamples
{
public void DemonstrateLinq()
{
var numbers = Enumerable.Range(1, 100).ToList();
var words = new[] { "hello", "world", "linq", "csharp" };
// Filter and transform
var evenSquares = numbers
.Where(n => n % 2 == 0)
.Select(n => n * n)
.ToList();
// Group by length
var wordGroups = words
.GroupBy(w => w.Length)
.Select(g => new {
Length = g.Key,
Words = g.ToList()
});
// Aggregate operations
var sum = numbers.Sum();
var avg = numbers.Average();
var max = numbers.Max();
// Custom aggregation
var customAggregate = words
.Aggregate("", (current, next) =>
current + (current.Length > 0 ? ", " : "") + next);
}
}
utilityintermediatedata-manipulation
Pranay Decsharp
Responsive HTML Layout
Modern responsive layout using HTML5 semantic elements
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Layout</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
<main>
<section id="hero">
<h1>Welcome to Our Site</h1>
<p>Discover amazing content</p>
</section>
<section id="features">
<article>
<h2>Feature 1</h2>
<p>Description of feature 1</p>
</article>
<article>
<h2>Feature 2</h2>
<p>Description of feature 2</p>
</article>
</section>
</main>
<footer>
<p>© 2024 Your Company</p>
</footer>
</body>
</html>
webbeginnertutorial
Amitava Dattahtml
Modern Card Design
Stylish card component with hover effects using CSS
.card {
background: var(--card-bg, #ffffff);
border-radius: 16px;
padding: 1.5rem;
box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
transition: all 0.3s ease;
position: relative;
overflow: hidden;
}
.card::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(
135deg,
rgba(255, 255, 255, 0.1),
rgba(255, 255, 255, 0.05)
);
opacity: 0;
transition: opacity 0.3s ease;
}
.card:hover {
transform: translateY(-4px);
box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1);
}
.card:hover::before {
opacity: 1;
}
.card-title {
font-size: 1.25rem;
font-weight: 600;
margin-bottom: 1rem;
color: var(--title-color, #1a1a1a);
}
.card-content {
font-size: 1rem;
line-height: 1.5;
color: var(--content-color, #4a4a4a);
}
@media (prefers-color-scheme: dark) {
.card {
--card-bg: #1a1a1a;
--title-color: #ffffff;
--content-color: #a0a0a0;
}
}
webcssdesignbeginner
Pranay Decss