Text Generation
English
code
File size: 4,782 Bytes
dae52e5
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
{"text": "def reverse_linked_list(head):\n    \"\"\"Reverse a singly linked list.\n    Time: O(n), Space: O(1)\n    \"\"\"\n    prev = None\n    current = head\n    while current:\n        next_node = current.next\n        current.next = prev\n        prev = current\n        current = next_node\n    return prev", "lang": "python", "source": "github"}
{"text": "def binary_search(arr, target):\n    \"\"\"Binary search on a sorted array.\"\"\"\n    left, right = 0, len(arr) - 1\n    while left <= right:\n        mid = (left + right) // 2\n        if arr[mid] == target:\n            return mid\n        elif arr[mid] < target:\n            left = mid + 1\n        else:\n            right = mid - 1\n    return -1", "lang": "python", "source": "github"}
{"text": "class Stack:\n    def __init__(self):\n        self.items = []\n\n    def push(self, item):\n        self.items.append(item)\n\n    def pop(self):\n        if not self.is_empty():\n            return self.items.pop()\n        raise IndexError('Stack is empty')\n\n    def peek(self):\n        if not self.is_empty():\n            return self.items[-1]\n        raise IndexError('Stack is empty')\n\n    def is_empty(self):\n        return len(self.items) == 0\n\n    def size(self):\n        return len(self.items)", "lang": "python", "source": "github"}
{"text": "function quickSort(arr) {\n  if (arr.length <= 1) return arr;\n  const pivot = arr[Math.floor(arr.length / 2)];\n  const left = arr.filter(x => x < pivot);\n  const middle = arr.filter(x => x === pivot);\n  const right = arr.filter(x => x > pivot);\n  return [...quickSort(left), ...middle, ...quickSort(right)];\n}", "lang": "javascript", "source": "github"}
{"text": "async function fetchWithRetry(url, maxRetries = 3) {\n  for (let attempt = 0; attempt < maxRetries; attempt++) {\n    try {\n      const response = await fetch(url);\n      if (!response.ok) throw new Error(`HTTP ${response.status}`);\n      return await response.json();\n    } catch (err) {\n      if (attempt === maxRetries - 1) throw err;\n      await new Promise(r => setTimeout(r, 1000 * Math.pow(2, attempt)));\n    }\n  }\n}", "lang": "javascript", "source": "github"}
{"text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nint binarySearch(const std::vector<int>& arr, int target) {\n    int left = 0, right = arr.size() - 1;\n    while (left <= right) {\n        int mid = left + (right - left) / 2;\n        if (arr[mid] == target) return mid;\n        if (arr[mid] < target) left = mid + 1;\n        else right = mid - 1;\n    }\n    return -1;\n}", "lang": "cpp", "source": "github"}
{"text": "public class Fibonacci {\n    // Memoized fibonacci\n    private static Map<Integer, Long> memo = new HashMap<>();\n\n    public static long fib(int n) {\n        if (n <= 1) return n;\n        if (memo.containsKey(n)) return memo.get(n);\n        long result = fib(n - 1) + fib(n - 2);\n        memo.put(n, result);\n        return result;\n    }\n}", "lang": "java", "source": "github"}
{"text": "func mergeSort(arr []int) []int {\n\tif len(arr) <= 1 {\n\t\treturn arr\n\t}\n\tmid := len(arr) / 2\n\tleft := mergeSort(arr[:mid])\n\tright := mergeSort(arr[mid:])\n\treturn merge(left, right)\n}\n\nfunc merge(left, right []int) []int {\n\tresult := make([]int, 0, len(left)+len(right))\n\tfor len(left) > 0 && len(right) > 0 {\n\t\tif left[0] <= right[0] {\n\t\t\tresult = append(result, left[0])\n\t\t\tleft = left[1:]\n\t\t} else {\n\t\t\tresult = append(result, right[0])\n\t\t\tright = right[1:]\n\t\t}\n\t}\n\treturn append(result, append(left, right...)...)\n}", "lang": "go", "source": "github"}
{"prompt": "Write a Python decorator that measures execution time", "completion": "import time\nfrom functools import wraps\n\ndef timeit(func):\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        start = time.perf_counter()\n        result = func(*args, **kwargs)\n        elapsed = time.perf_counter() - start\n        print(f'{func.__name__} took {elapsed:.4f}s')\n        return result\n    return wrapper\n\n# Usage:\n@timeit\ndef slow_function():\n    time.sleep(1)\n    return 'done'", "lang": "python"}
{"prompt": "Create a TypeScript generic function to remove duplicates from an array", "completion": "function removeDuplicates<T>(arr: T[]): T[] {\n  return [...new Set(arr)];\n}\n\n// For objects, use a key extractor:\nfunction removeDuplicatesBy<T, K>(arr: T[], keyFn: (item: T) => K): T[] {\n  const seen = new Set<K>();\n  return arr.filter(item => {\n    const key = keyFn(item);\n    if (seen.has(key)) return false;\n    seen.add(key);\n    return true;\n  });\n}\n\n// Usage:\nconst nums = removeDuplicates([1, 2, 2, 3, 3, 4]); // [1, 2, 3, 4]\nconst users = removeDuplicatesBy(users, u => u.id);", "lang": "typescript"}