nova / programming.txt
crazysanthosh's picture
Upload 25 files
7fde9b9 verified
Raw History Blame Contribute Delete
10.9 kB
## Variables and Data Types
Definition: Variables are named containers that store data values. Data types define what kind of data a variable holds — numbers, text, booleans, etc.
Explanation: Every programming language has data types. In statically typed languages (Java, C++), the type is declared at compile time. In dynamically typed languages (Python, JavaScript), the type is inferred at runtime. Common types include integers, floats, strings, booleans, arrays, and objects.
Example: In Python, x = 10 creates an integer variable. In JavaScript, let name = "NOVA" creates a string.
Code Example:
```python
# Python examples
x = 42 # int
name = "NOVA" # str
pi = 3.14 # float
flag = True # bool
items = [1,2,3] # list
```
Best Practices: Use descriptive variable names. Avoid single-letter names except in short loops. Prefer constants (ALL_CAPS) for fixed values.
Common Errors: Using a variable before declaring it. Assigning the wrong type (e.g., passing a string where a number is expected).
Interview Questions: What is the difference between strongly typed and weakly typed languages? Explain type coercion in JavaScript.
## Functions and Methods
Definition: A function is a reusable block of code that performs a specific task. Methods are functions defined inside a class.
Explanation: Functions promote DRY (Don't Repeat Yourself) principles. They take inputs (parameters), perform operations, and optionally return a value. Functions can be pure (no side effects) or impure. Higher-order functions take or return other functions.
Example: A function that adds two numbers and returns the result.
Code Example:
```javascript
// Pure function - no side effects
function add(a, b) {
return a + b;
}
// Arrow function (ES6+)
const multiply = (x, y) => x * y;
// Higher-order function
const applyTwice = (fn, val) => fn(fn(val));
console.log(applyTwice(x => x * 2, 3)); // 12
```
Best Practices: Keep functions small and focused on one task. Use clear parameter names. Avoid side effects in pure functions.
Common Errors: Forgetting to return a value. Incorrect scope of variables inside functions. Infinite recursion without a base case.
Interview Questions: What is the difference between a function declaration and a function expression? What is a closure? What are pure functions?
## Object-Oriented Programming
Definition: OOP is a programming paradigm that organizes code around objects, which encapsulate data (attributes) and behavior (methods).
Explanation: The four pillars of OOP are: Encapsulation (bundling data and methods), Abstraction (hiding complex details), Inheritance (child classes reuse parent class code), and Polymorphism (same interface, different behavior). OOP helps model real-world entities and build maintainable, scalable code.
Example: A Car class with attributes like make and model, and methods like startEngine().
Code Example:
```python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
d = Dog("Rex")
print(d.speak()) # Rex says Woof!
```
Best Practices: Favor composition over inheritance when possible. Keep classes cohesive (single responsibility). Use interfaces/abstract classes for polymorphism.
Common Errors: Overusing inheritance (deep hierarchies become fragile). Not calling super().__init__() in Python. Mutating shared state through objects.
Interview Questions: Explain the 4 pillars of OOP. What is the difference between an abstract class and an interface? What is method overriding vs overloading?
## Algorithms and Big O Notation
Definition: An algorithm is a step-by-step procedure to solve a problem. Big O notation describes how the runtime or memory of an algorithm scales with input size.
Explanation: Common Big O complexities: O(1) constant, O(log n) logarithmic (binary search), O(n) linear, O(n log n) efficient sorting, O(n²) quadratic (nested loops), O(2^n) exponential. Lower = better performance. Analyzing complexity helps choose the right algorithm for the scale.
Example: Linear search is O(n). Binary search on a sorted array is O(log n).
Code Example:
```python
# O(n) - Linear Search
def linear_search(arr, target):
for i, item in enumerate(arr):
if item == target:
return i
return -1
# O(log n) - Binary Search
def binary_search(arr, target):
lo, hi = 0, len(arr) - 1
while lo <= hi:
mid = (lo + hi) // 2
if arr[mid] == target: return mid
elif arr[mid] < target: lo = mid + 1
else: hi = mid - 1
return -1
```
Best Practices: Always consider time AND space complexity. Profile before optimizing. Know the complexity of built-in operations (e.g., list.insert() is O(n) in Python).
Common Errors: Nested loops where a hash map could reduce to O(n). Copying large arrays unnecessarily. Ignoring space complexity when optimizing for time.
Interview Questions: What is the time complexity of quick sort in the worst case? How does a hash map achieve O(1) average lookup? Explain amortized complexity.
## Recursion
Definition: Recursion is when a function calls itself to solve a smaller subproblem until it reaches a base case.
Explanation: Every recursive solution has two parts: a base case (the stopping condition) and a recursive case (the self-call with a smaller input). Recursion is elegant for tree traversal, divide-and-conquer, and problems with natural recursive structure. It uses the call stack, so deep recursion can cause stack overflow.
Example: Fibonacci sequence, factorial, tree traversal, merge sort.
Code Example:
```python
def factorial(n):
if n <= 1: # Base case
return 1
return n * factorial(n - 1) # Recursive case
# Fibonacci with memoization
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2: return n
return fib(n-1) + fib(n-2)
print(fib(50)) # Fast!
```
Best Practices: Always define a clear base case. Use memoization (dynamic programming) to avoid redundant computation. Consider iterative solutions if stack depth is a concern.
Common Errors: Missing or incorrect base case causes infinite recursion. Not reducing the problem size in the recursive call. Stack overflow for very deep recursion.
Interview Questions: How do you convert a recursive solution to an iterative one? Explain tail recursion. What is memoization?
## Design Patterns
Definition: Design patterns are reusable solutions to commonly occurring software design problems. They are templates, not finished code.
Explanation: Patterns are categorized into Creational (object creation), Structural (object composition), and Behavioral (communication between objects). Famous examples include Singleton, Factory, Observer, Strategy, and Decorator. They improve code readability and reduce duplication.
Example: The Observer pattern is used in event systems — subscribers are notified when an event occurs.
Code Example:
```python
# Singleton Pattern
class Database:
_instance = None
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
db1 = Database.get_instance()
db2 = Database.get_instance()
print(db1 is db2) # True - same instance
```
Best Practices: Don't force patterns. Apply them when they naturally solve the problem. Favor the Strategy pattern over complex if-else chains. Use dependency injection for flexibility.
Common Errors: Over-engineering with patterns when simple code suffices. Misapplying the Singleton pattern causes global state issues. Confusing Decorator pattern with Python decorators.
Interview Questions: What is the difference between Factory and Abstract Factory? Explain the Strategy pattern. When would you use the Observer pattern?
## Data Structures
Definition: Data structures are ways of organizing and storing data so it can be accessed and modified efficiently.
Explanation: Key data structures include: Arrays/Lists (indexed, O(1) access), Linked Lists (O(n) access, O(1) insert at head), Stacks (LIFO — last in first out), Queues (FIFO), Hash Maps (O(1) average lookup), Trees (hierarchical), Graphs (network relationships), Heaps (priority queues).
Example: A hash map stores user sessions by ID for O(1) lookup. A queue manages task scheduling.
Code Example:
```python
# Stack using list
stack = []
stack.append(1) # push
stack.append(2)
top = stack.pop() # pop -> 2
# Queue using deque
from collections import deque
q = deque()
q.append("a")
q.append("b")
front = q.popleft() # "a"
# Hash Map
cache = {}
cache["user_1"] = {"name": "Alice"}
print(cache.get("user_1"))
```
Best Practices: Choose the right structure for the access pattern. Use deque for queues, not list.pop(0). Prefer dicts over lists for key-based lookup.
Common Errors: Using a list for frequent membership checks (use a set instead). Not accounting for hash collisions. Misunderstanding tree vs graph.
Interview Questions: What is the difference between a stack and a queue? How does a hash table handle collisions? Explain a binary search tree.
## Sorting Algorithms
Definition: Sorting algorithms arrange elements of a list in a specific order (ascending/descending).
Explanation: Common sorts: Bubble Sort O(n²) — simple but slow. Merge Sort O(n log n) — divide and conquer, stable. Quick Sort O(n log n) avg — in-place, fastest in practice. Heap Sort O(n log n) — uses a heap. Counting Sort O(n+k) — non-comparison, great for integers in a known range. Python's sorted() uses Timsort (hybrid merge + insertion sort).
Example: Sorting a list of 1 million names — Quick Sort or Merge Sort is required; Bubble Sort would be too slow.
Code Example:
```python
# Merge Sort
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
return result + left[i:] + right[j:]
```
Best Practices: Use built-in sorts in production (they're optimized). Understand when a stable sort matters (preserving order of equal elements). Use counting/radix sort for integer-range data.
Common Errors: Implementing Quick Sort without a good pivot strategy (worst case O(n²) on sorted input). Forgetting that Merge Sort requires O(n) extra space.
Interview Questions: What makes Merge Sort stable? Explain the partition step in Quick Sort. When would you use Counting Sort over comparison-based sorts?