CodeSage / data /reference_answers.json
Aditya
Major upgrade: 50-question benchmark, persistent analytics, paper-style TABLE II
900c573
Raw
History Blame Contribute Delete
19.5 kB
{
"what is binary search?": "Binary search is an efficient searching algorithm for sorted arrays. It works by repeatedly dividing the search interval in half. Time complexity: O(log n), Space complexity: O(1). Requires the array to be sorted beforehand.",
"what is the time complexity of binary search?": "Binary search has a time complexity of O(log n) because it halves the search space with each step. Best case is O(1) when the middle element is the target. Space complexity is O(1) for iterative implementation.",
"what is the difference between stack and queue?": "Stack uses LIFO (Last In First Out) - the last element added is the first to be removed. Operations: push and pop. Queue uses FIFO (First In First Out) - the first element added is the first to be removed. Operations: enqueue and dequeue. Both have O(1) operations.",
"stack vs queue?": "Stack uses LIFO (Last In First Out) - the last element added is the first to be removed. Operations: push and pop. Queue uses FIFO (First In First Out) - the first element added is the first to be removed. Operations: enqueue and dequeue. Both have O(1) operations.",
"explain merge sort.": "Merge sort is a divide-and-conquer sorting algorithm. It splits the array in half, recursively sorts each half, then merges the two sorted halves. Time complexity: O(n log n) in all cases. Space complexity: O(n). It is a stable sorting algorithm, making it good for sorting linked lists.",
"what is quicksort?": "Quicksort is a divide-and-conquer algorithm that picks a pivot element and partitions the array into elements less than and greater than the pivot, then recursively sorts each partition. Average time: O(n log n), Worst case: O(n^2) when pivot is always smallest or largest element. Space: O(log n).",
"what is a linked list?": "A linked list is a linear data structure where elements are stored in nodes. Each node contains data and a pointer to the next node. Types: Singly (one direction), Doubly (both directions), Circular (last points to first). Advantage: dynamic size, O(1) insertion at head. Disadvantage: no random access, O(n) search.",
"what is a binary search tree?": "A Binary Search Tree (BST) is a binary tree where for every node, all values in the left subtree are less than the node's value, and all values in the right subtree are greater. This property enables O(log n) average search, insert, and delete operations. Worst case is O(n) for unbalanced trees.",
"what is dynamic programming?": "Dynamic programming solves complex problems by breaking them into overlapping subproblems and storing results to avoid recomputation. Two approaches: Memoization (top-down, recursion with cache) and Tabulation (bottom-up, iterative). Requires optimal substructure and overlapping subproblems. Examples: Fibonacci, Knapsack, LCS, Coin Change.",
"what are react hooks?": "React hooks are functions that let you use state and lifecycle features in functional components, introduced in React 16.8. Key hooks: useState for state management, useEffect for side effects like API calls, useContext for consuming context, useRef for DOM references. Rules: only call hooks at top level, only in React functions.",
"what is usestate in react?": "useState is a React hook for managing local component state. Syntax: const [state, setState] = useState(initialValue). It returns the current state value and a setter function. Calling setState triggers a re-render with the new value. Example: const [count, setCount] = useState(0) then setCount(count + 1) to increment.",
"what is useeffect in react?": "useEffect is a React hook for handling side effects like API calls, subscriptions, and DOM updates. It runs after every render by default. The dependency array controls when it runs: empty array [] runs only on mount, [value] runs when value changes. Return a cleanup function to run on unmount. Syntax: useEffect(() => { effect }, [deps]).",
"what is a rest api?": "REST API (Representational State Transfer) is an architectural style for web services using standard HTTP methods. GET retrieves resources, POST creates new resources, PUT updates resources completely, PATCH partially updates, DELETE removes resources. REST is stateless meaning each request contains all needed information. JSON is the most common response format.",
"what http methods does rest use?": "REST uses five main HTTP methods: GET for reading/retrieving data, POST for creating new resources, PUT for completely updating an existing resource, PATCH for partially updating a resource, and DELETE for removing a resource. These map to CRUD operations: Create (POST), Read (GET), Update (PUT/PATCH), Delete (DELETE).",
"what does http status code 404 mean?": "HTTP status code 404 means Not Found. It indicates the server cannot find the requested resource. The URL may be wrong, the resource may have been deleted, or it may never have existed. Other important codes: 200 (OK), 201 (Created), 400 (Bad Request), 401 (Unauthorized), 403 (Forbidden), 500 (Internal Server Error).",
"what is css flexbox?": "CSS Flexbox is a layout model that makes it easy to arrange items in a container. Activated by display: flex on the container. Key properties: flex-direction (row or column), justify-content (main axis alignment: flex-start, center, space-between), align-items (cross axis: stretch, center, flex-start), flex-wrap (allow wrapping). Items can have flex-grow to fill available space.",
"what is a javascript promise?": "A JavaScript Promise represents an asynchronous operation with three states: pending (initial), fulfilled (success), rejected (failure). Created with new Promise((resolve, reject) => {}). Consumed with .then() for success and .catch() for errors. async/await is syntactic sugar that makes promises look synchronous. Promise.all() runs multiple promises in parallel.",
"what is inorder traversal?": "Inorder traversal visits tree nodes in Left, Root, Right order. For a Binary Search Tree, inorder traversal produces nodes in ascending sorted order. Algorithm: recursively visit left subtree, then process current node, then recursively visit right subtree. Time complexity: O(n) where n is number of nodes.",
"what is the difference between bfs and dfs?": "BFS (Breadth-First Search) explores level by level using a queue data structure. It finds shortest path in unweighted graphs. DFS (Depth-First Search) explores as deep as possible using a stack or recursion. BFS is better for shortest path problems; DFS is better for cycle detection, topological sort, and finding connected components. Both have O(V+E) time complexity.",
"what is memoization?": "Memoization is a top-down dynamic programming technique that caches results of expensive function calls and returns the cached result when the same inputs occur again. It uses recursion combined with a hash map or array to store computed values. For example, Fibonacci with memoization runs in O(n) instead of O(2^n). It trades space for time.",
"what is flex-grow in css?": "flex-grow is a CSS Flexbox property that defines how much a flex item grows relative to other items when extra space is available in the container. A value of 0 means the item will not grow. A value of 1 means the item takes equal share of available space. If one item has flex-grow: 2 and another has flex-grow: 1, the first gets twice as much extra space.",
"what is a hash table?": "A hash table is a data structure that maps keys to values using a hash function to compute an index into an array of buckets. Average time complexity: O(1) for insert, delete, and lookup. Worst case O(n) due to collisions. Collision resolution strategies: chaining (linked lists at each bucket) or open addressing (linear probing, quadratic probing).",
"what is time complexity?": "Time complexity measures how the runtime of an algorithm grows relative to input size n. Expressed using Big O notation. Common complexities from fastest to slowest: O(1) constant, O(log n) logarithmic, O(n) linear, O(n log n) linearithmic, O(n^2) quadratic, O(2^n) exponential. It describes the worst-case upper bound on runtime.",
"what is space complexity?": "Space complexity measures the amount of memory an algorithm uses relative to input size. Includes both auxiliary space (extra space used by algorithm) and input space. Expressed in Big O notation. Example: merge sort uses O(n) auxiliary space, in-place quicksort uses O(log n) for the call stack. Constant O(1) space means the algorithm uses fixed memory regardless of input size.",
"what is recursion?": "Recursion is a technique where a function calls itself to solve smaller instances of the same problem. Every recursive function needs a base case (termination condition) to stop infinite calls and a recursive case that moves toward the base case. Examples: factorial, Fibonacci, tree traversal. Recursion uses the call stack so deep recursion can cause stack overflow.",
"what is a heap data structure?": "A heap is a complete binary tree satisfying the heap property. Max-heap: every parent is greater than or equal to its children. Min-heap: every parent is less than or equal to its children. Implemented as an array. Key operations: insert O(log n), extract-min/max O(log n), peek O(1). Used in priority queues, heap sort, and Dijkstra's algorithm.",
"what is a graph data structure?": "A graph is a collection of vertices (nodes) connected by edges. Types: directed (edges have direction), undirected (bidirectional edges), weighted (edges have values), unweighted. Representations: adjacency matrix O(V^2) space, adjacency list O(V+E) space. Traversal algorithms: BFS and DFS. Applications: social networks, navigation, dependency resolution.",
"what is depth first search?": "Depth First Search (DFS) is a graph traversal algorithm that explores as far as possible along each branch before backtracking. Uses a stack (or recursion). Time complexity: O(V+E). Applications: cycle detection, topological sort, finding connected components, solving mazes, path finding. Can be implemented iteratively using an explicit stack or recursively.",
"what is breadth first search?": "Breadth First Search (BFS) is a graph traversal algorithm that explores all neighbors at the current depth before moving to nodes at the next depth level. Uses a queue. Time complexity: O(V+E). Finds shortest path in unweighted graphs. Applications: shortest path, level-order tree traversal, web crawlers, social network friend suggestions.",
"what is a hash map?": "A hash map (also called hash table or dictionary) is a data structure that stores key-value pairs with O(1) average time for insert, lookup, and delete operations. A hash function converts keys into array indices. Collisions (multiple keys mapping to same index) are handled via chaining or open addressing. In Python it is dict, in Java HashMap, in JavaScript plain objects or Map.",
"what is big o notation?": "Big O notation describes the upper bound on an algorithm's time or space complexity as input size grows toward infinity. It ignores constants and lower-order terms. Common classes: O(1) constant, O(log n) logarithmic (binary search), O(n) linear (linear search), O(n log n) merge sort, O(n^2) bubble sort, O(2^n) exponential. Used to compare algorithm efficiency.",
"what is a tree data structure?": "A tree is a hierarchical data structure with a root node and subtrees of children connected by edges. Key terms: root (topmost node), leaf (node with no children), height (longest path from root to leaf), depth (distance from root). Types: binary tree (max 2 children), BST, AVL tree, B-tree, trie. Operations like search/insert are O(log n) for balanced trees.",
"what is object oriented programming?": "Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects containing data (attributes) and behavior (methods). Four pillars: Encapsulation (bundling data and methods, hiding internal state), Inheritance (child classes inherit from parent), Polymorphism (same interface, different implementations), Abstraction (hiding complex implementation details). Languages: Java, Python, C++, JavaScript.",
"what is inheritance in oop?": "Inheritance is an OOP concept where a child class (subclass) derives properties and methods from a parent class (superclass). Promotes code reuse and hierarchical relationships. Child class can override parent methods. Types: single (one parent), multiple (multiple parents, supported in Python but not Java), multilevel (chain of inheritance). Syntax in Python: class Child(Parent).",
"what is polymorphism in oop?": "Polymorphism means 'many forms' - the same interface can be used for different underlying data types. Two types: compile-time (method overloading - same name, different parameters) and runtime (method overriding - child class redefines parent method). Enables writing generic code that works with multiple types. Example: a speak() method behaves differently for Dog vs Cat objects.",
"what is encapsulation in oop?": "Encapsulation bundles data (attributes) and the methods that operate on that data within a single unit (class), and restricts direct access to some components. Access modifiers: public (accessible everywhere), private (class only), protected (class and subclasses). Achieved using getters and setters in Java, name mangling (__attr) in Python. Protects data integrity and hides implementation details.",
"what is async await in javascript?": "async/await is syntactic sugar over Promises that makes asynchronous code look synchronous. A function marked async always returns a Promise. The await keyword pauses execution inside an async function until the awaited Promise resolves. Error handling uses try/catch. Example: async function fetchData() { try { const res = await fetch(url); return await res.json(); } catch(e) { console.error(e); } }",
"what is a closure in javascript?": "A closure is a function that retains access to its outer (enclosing) scope even after the outer function has returned. The inner function 'closes over' the variables from its lexical environment. Used for data privacy, factory functions, and callbacks. Example: function counter() { let count = 0; return function() { return ++count; }; } - the returned function remembers count.",
"what is the event loop in javascript?": "The JavaScript event loop is the mechanism that allows non-blocking async operations in a single-threaded environment. The call stack executes synchronous code. Async operations (setTimeout, fetch) are handled by Web APIs and their callbacks are queued in the callback queue (or microtask queue for Promises). The event loop continuously checks if the call stack is empty, then pushes queued callbacks onto it.",
"what is typescript?": "TypeScript is a statically typed superset of JavaScript developed by Microsoft. It adds optional static typing, interfaces, enums, generics, and decorators. TypeScript code compiles (transpiles) to plain JavaScript. Benefits: catch type errors at compile time, better IDE support, improved code documentation via type annotations. Example: function greet(name: string): string { return 'Hello ' + name; }",
"what is sql?": "SQL (Structured Query Language) is a domain-specific language for managing relational databases. Key statements: SELECT (query data), INSERT (add rows), UPDATE (modify rows), DELETE (remove rows), CREATE TABLE (define schema), JOIN (combine tables). Supports filtering with WHERE, grouping with GROUP BY, sorting with ORDER BY. Databases: MySQL, PostgreSQL, SQLite, SQL Server.",
"what is a primary key in sql?": "A primary key is a column (or set of columns) in a relational table that uniquely identifies each row. Constraints: values must be unique and cannot be NULL. Each table can have only one primary key. Used to enforce entity integrity and as a reference point for foreign keys in other tables. Auto-incrementing integers or UUIDs are common primary key types.",
"what is a foreign key in sql?": "A foreign key is a column in one table that references the primary key of another table, establishing a link between the two tables. Enforces referential integrity - you cannot insert a foreign key value that doesn't exist in the referenced table. Used to model relationships: one-to-many, many-to-many (via junction table). ON DELETE CASCADE automatically deletes child rows when the parent row is deleted.",
"what is an index in sql?": "A database index is a data structure (typically a B-tree) that improves the speed of data retrieval operations on a table column at the cost of additional storage and slower writes. Without an index, queries do a full table scan O(n). With an index, lookups become O(log n). Primary keys are automatically indexed. Create with: CREATE INDEX idx_name ON table(column). Avoid over-indexing as it slows inserts and updates.",
"what is normalization in databases?": "Database normalization is the process of organizing tables to reduce redundancy and improve data integrity. Normal forms: 1NF (atomic values, no repeating groups), 2NF (no partial dependencies on composite keys), 3NF (no transitive dependencies), BCNF (every determinant is a candidate key). Normalization avoids update, insert, and delete anomalies but may require more joins in queries.",
"what is git?": "Git is a distributed version control system that tracks changes in source code. Key concepts: repository (project history), commit (snapshot of changes), branch (parallel line of development), merge (combining branches), clone (copy repository), push/pull (sync with remote). Created by Linus Torvalds in 2005. Platforms: GitHub, GitLab, Bitbucket host remote Git repositories.",
"what is a merge conflict in git?": "A merge conflict occurs in Git when two branches modify the same part of a file differently and Git cannot automatically determine which change to keep. Conflicts are marked with <<<<<<, =======, and >>>>>>> in the file. Resolution: manually edit the file to keep the desired changes, remove conflict markers, then stage and commit the resolved file. Use git status to see conflicted files.",
"what is docker?": "Docker is a platform for building, shipping, and running applications in containers. A container is a lightweight, isolated environment that packages the application and its dependencies. Key concepts: Dockerfile (instructions to build an image), image (read-only template), container (running instance of an image), Docker Hub (public image registry). Containers are portable across environments and start in milliseconds.",
"what is json?": "JSON (JavaScript Object Notation) is a lightweight, human-readable data interchange format based on JavaScript object syntax. Supports six data types: string, number, boolean, null, array, and object. Example: {\"name\": \"Alice\", \"age\": 30, \"skills\": [\"Python\", \"SQL\"]}. Widely used in REST APIs and configuration files. Parsed in Python with json.loads(), in JavaScript with JSON.parse().",
"what is css grid?": "CSS Grid is a two-dimensional layout system that organizes content into rows and columns. Activated with display: grid. Key properties: grid-template-columns (define column sizes), grid-template-rows, gap (spacing between cells), grid-column/grid-row (span multiple cells), grid-area (named placement). More powerful than Flexbox for complex 2D layouts. Use Flexbox for 1D (row or column) layouts, Grid for 2D."
}