Programming concepts Flashcards

(138 cards)

1
Q

What is data normalization?

A

Data normalization in programming is the process of organizing and structuring data within a database to reduce redundancy, eliminate anomalies, and enhance overall data integrity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are main objectives of data normalization?

A

The main objectives of data normalization are:
- Reduce data redundancy and improve data integrity.
- Eliminate undesirable insertion, update, and deletion dependencies.
- Make the database more informative and adaptable to changes.
- Enhance the efficiency of data storage and retrieval.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are benefits of data normalization? (4)

A
  1. Improved data consistency and accuracy.
  2. Reduced data redundancy and storage requirements.
  3. Easier data maintenance and updates5.
  4. Enhanced query performance and data analysis capabilities3.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the 3 normal forms in data normalization?

A

First Normal Form (1NF)
- Ensures that each column contains atomic (indivisible) values.
Eliminates repeating groups and ensures each row is unique2.

Second Normal Form (2NF)
- Builds on 1NF by ensuring all non-key attributes are fully dependent on the primary key.
- Requires the creation of separate tables for subsets of data that apply to multiple rows.

Third Normal Form (3NF)
- Eliminates transitive dependencies between non-key attributes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are the 5 kind of relationships in databases?

A

One-to-One (1:1) Relationship
One-to-Many (1:M) Relationship
Many-to-One (M:1) Relationship
Many-to-Many (M:M) Relationship
Self-Referencing (Recursive) Relationship

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

One-to-One (1:1) Relationship

A

Definition: In this relationship, each record in one table is associated with exactly one record in another table.

Example: A person has one passport. Each passport is assigned to exactly one person.

Use Case: This relationship is used when one entity is closely linked to another, and both share a unique identifier.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

One-to-Many (1:M) Relationship

A

Definition: In a one-to-many relationship, a single record in one table can be associated with multiple records in another table, but each record in the second table is associated with only one record in the first table.

Example: A department can have many employees, but each employee belongs to only one department.

Use Case: This is the most common type of relationship. It is typically used to represent parent-child relationships between entities.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Many-to-One (M:1) Relationship

A

Definition: This is essentially the reverse of the one-to-many relationship. Many records in one table can be linked to a single record in another table.

Example: Many employees work in one department. Here, each employee belongs to one department, but a department can have many employees.

Use Case: This is used when multiple entities point to a single entity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Many-to-Many (M:M) Relationship

A

Definition: In this relationship, many records in one table can be related to many records in another table. This is often implemented using a junction (or associative) table that holds the foreign keys of both related tables.

Example: A student can enroll in many courses, and a course can have many students.

Use Case: This relationship is used when entities are mutually related and both sides can have multiple associations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Self-Referencing (Recursive) Relationship (in databases)

A

Definition: This is when a table has a relationship with itself. This can represent hierarchical or recursive relationships within the same table.

Example: An employee manages other employees. The “employees” table would have a “manager_id” column that references the same table.

Use Case: Used for hierarchical structures or when an entity has relationships with other instances of the same entity (e.g., an organizational structure).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is A/B testing?

A

A/B testing is a method of comparing two versions of a webpage, app, or other variable to determine which one performs better. It involves randomly showing different variants to users and using statistical analysis to measure which version achieves better results for specific conversion goals.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Why would you use generators instead of list/arrays in Python/JS? (3)

A
  1. Memory Efficiency
  2. Working with a big files
  3. Creating Infinite Sequences
  4. Generators are substantially more memory efficient than lists or arrays because they generate values on-the-fly rather than storing the entire sequence in memory at once.
  5. Generators employ lazy evaluation, computing values only when requested through iteration
  6. def infinite_counter():
    i = 0
    while True:
    yield i
    i += 1

4.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What does the ‘S’ in SOLID stand for?

A

Single Responsibility Principle

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the main idea of the Single Responsibility Principle?

A

A class should have only one reason to change

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How does the Single Responsibility Principle improve code?

A

By making classes easier to understand, test, and maintain

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is an example of a violation of the Single Responsibility Principle?

A

A class that handles both data processing and logging

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How can you implement the Single Responsibility Principle in Python?

A

By creating small classes that focus on a single task or responsibility

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How can you implement the Single Responsibility Principle in React?

A

By using functional components and hooks to separate concerns

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How does the Single Responsibility Principle relate to design patterns?

A

Many design patterns, like MVC (Model-View-Controller), promote this principle

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What does the ‘O’ in SOLID stand for?

A

Open/Closed Principle

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the Open/Closed Principle?

A

Software entities should be open for extension but closed for modification

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How can you apply the Open/Closed Principle in Python?

A

By using abstract base classes or interfaces and extending them

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is an example of the Open/Closed Principle in React?

A

Using higher-order components to add functionality without modifying existing components

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is a violation of the Open/Closed Principle?

A

Modifying existing classes to add new features instead of extending them

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
How does the Open/Closed Principle relate to design patterns?
Many design patterns, like Strategy and Decorator, support this principle
26
What does the 'L' in SOLID stand for?
Liskov Substitution Principle
27
What is the Liskov Substitution Principle?
The Liskov Substitution Principle (LSP) states that subclasses must be interchangeable with their parent classes without breaking code or altering expected behavior.
28
How can you violate the Liskov Substitution Principle in Python?
By overriding a method in a subclass so it behaves differently than expected
29
How can you violate the Liskov Substitution Principle in React?
By using a component that does not adhere to the expected interface of its parent component
30
What does the 'I' in SOLID stand for?
Interface Segregation Principle
31
What is the Interface Segregation Principle?
Clients should not be forced to depend on interfaces they do not use
32
How can you follow the Interface Segregation Principle in Python?
By creating small, specific interfaces instead of large, general ones
33
What is an example of the Interface Segregation Principle in React?
Creating separate components for different functionalities instead of one large component
34
How can you violate the Interface Segregation Principle in Python?
By creating a large interface that forces clients to implement unnecessary methods
35
How can you violate the Interface Segregation Principle in React?
By creating a single component that handles multiple unrelated functionalities
36
What does the 'D' in SOLID stand for?
Dependency Inversion Principle
37
What is the Dependency Inversion Principle?
High-level modules should not depend on low-level modules; both should depend on abstractions
38
What is an example of Dependency Inversion in Python?
Using interfaces or abstract classes to define dependencies
39
What is an example of Dependency Inversion in React?
Using context providers to manage state instead of directly using state in components
40
What is an example of Dependency Inversion in Angular?
Using dependency injection to provide services to components
41
What is a common anti-pattern that violates the Dependency Inversion Principle?
Tightly coupling high-level and low-level modules
42
Why are SOLID principles important for developers?
They help create code that is maintainable, flexible, and scalable
43
Which SOLID principle helps avoid 'God classes'?
Single Responsibility Principle
44
Which SOLID principle encourages extending functionality without modifying existing code?
Open/Closed Principle
45
Which SOLID principle is most related to inheritance and polymorphism?
Liskov Substitution Principle
46
How does dependency injection relate to SOLID?
It supports the Dependency Inversion Principle by decoupling class dependencies
47
What is a common anti-pattern that violates the Single Responsibility Principle?
A class that handles both data storage and user interface logic
48
What is the main benefit of following SOLID principles in team projects?
It makes codebases easier to understand, modify, and scale collaboratively
49
How it works that when user enters password on registration it is saved as a hash and when he/she log in with this password it knows if the password is correct or no. It should require encoding hash password which means that passwords are readable if we know how they are decoded.
Yes, we are storing hashes of password, but we are not decoding them at any way, we cant take hash and make from them password again. Instead we are taking user password and decoding it to hash, then we compare if this two hashes are the same.
50
What is salt in terms of password auth?
A salt in cryptography is a random piece of data that is added to a password before it is processed by a hashing algorithm.
51
Why unique salt is required when generating password?
A salt’s role isn’t secrecy but uniqueness. Each salt forces attackers to recompute hashes individually, even for identical passwords.
52
Why every user should have unique salt saved to his record in user table? Why no only one the same salt for every password?
If we would use the same salt same password used by two different persons would be written in database as the same hashes. This raises security issues such us easy findings of users with potential easy passwords.
53
What is the main purpose of the Git worktree command?
To allow working on multiple Git branches simultaneously without stashing or switching.
54
In what situation is Git worktree especially useful?
When you have uncommitted WIP changes but need to work on another branch, such as a hotfix.
55
How does Git worktree store each branch?
In a separate specified folder in the file system.
56
What command is used to add a new worktree in Git?
git worktree add
57
What is the Ducin's quick definition of software architecture?
High-level technical decisions made according to business requirements that shape the system today and are difficult to change in the future
58
Why is directory structure not considered architecture?
Because it's an implementation detail used to achieve architectural goals, not a high-level decision itself
59
Give an example of an architectural decision in frontend systems.
Choosing between microfrontends and a monolith
60
Give an example of a technical decision in frontend systems.
Choosing Webpack Module Federation for microfrontends
61
What does CQRS stand for?
Command Query Responsibility Segregation
62
What is the main idea of CQRS?
Separates read (query) operations from write (command) operations into distinct models
63
What are Commands in CQRS?
Operations that change state, like create, update, delete; no data returned
64
What are Queries in CQRS?
Operations that retrieve data without changing state
65
How does CQRS differ from CRUD?
CRUD uses one model for reads/writes; CQRS uses separate optimized models
66
What is the write side in CQRS?
Handles commands, enforces business rules, updates write database
67
What is the read side in CQRS?
Optimized for queries, often uses denormalized data from read database
68
Name a benefit of CQRS.
Improved scalability and performance by optimizing read/write paths independently
69
What pattern often pairs with CQRS?
Event Sourcing, to log changes as events for rebuilding state
70
When to use CQRS?
Complex domains with high read/write loads or differing requirements
71
What is the average and worst-case time complexity of Quicksort, and is it stable?
Avg **O(n log n)**, worst **O(n²)**; in-place, **not stable**.
72
What is the time complexity and key property of Merge Sort?
**O(n log n)** guaranteed (all cases); **stable**; requires O(n) extra space.
73
What is the time complexity of Heapsort, and is it stable?
**O(n log n)**, in-place, **not stable**.
74
When should you prefer Merge Sort over Quicksort?
When **stability** is required, or worst-case O(n log n) is needed (e.g., sorting linked lists or external sorting).
75
Why is the lower bound for comparison-based sorting O(n log n)?
Must distinguish n! orderings; a binary decision tree needs at least log₂(n!) ≈ n log n levels.
76
What is BFS used for in graphs?
Finding the **shortest path in unweighted graphs**; level-order traversal of trees.
77
What is DFS used for in graphs?
**Cycle detection**, topological sort, connected components, backtracking, path existence.
78
What does Dijkstra's algorithm do, and what is its key constraint?
Finds **shortest path in weighted graphs**; requires **non-negative edge weights**.
79
How does A* differ from Dijkstra's algorithm?
A* uses a **heuristic** h(n) to estimate cost to goal, prioritizing promising paths — faster in practice when a good heuristic exists.
80
What is topological sort and when is it applicable?
A linear ordering of vertices so every edge u→v has u before v; only valid for **DAGs** (directed acyclic graphs).
81
What problem does Union-Find (DSU) solve?
Efficiently tracks connected components; supports **union** (merge sets) and **find** (get representative). Used for cycle detection and Kruskal's MST.
82
What is the time complexity of Union-Find with path compression + union by rank?
Amortized **O(α(n))** per operation, where α is the inverse Ackermann function — effectively O(1).
83
What are the two conditions that indicate a problem can be solved with Dynamic Programming?
**Overlapping subproblems** + **optimal substructure**.
84
What is the difference between memoization and tabulation in DP?
Memoization = **top-down** (recursive + cache hits). Tabulation = **bottom-up** (iterative, fill table from base cases up).
85
Name four classic DP problem patterns.
**Knapsack**, **Longest Common Subsequence (LCS)**, **Coin Change**, **Edit Distance**.
86
What is the backtracking template structure?
**Choose → Explore → Unchoose**: add to state, recurse, then undo the choice (remove from state).
87
What is "binary search on the answer"?
Binary search over the **answer space** (a range of values), using a feasibility predicate to determine if a candidate answer is valid.
88
How do you binary search for the **first** occurrence of target in a sorted array?
When `arr[mid] == target`, don't return early — set `right = mid` and continue narrowing left until `left == right`.
89
What is the two-pointer technique? (algorithms)
Place two pointers (left/right or slow/fast) that move toward or past each other. Works on **sorted arrays**; also used for palindrome checks and pair sums.
90
What is the sliding window technique? (algorithms)
Maintain a window `[left, right]`; expand `right`, shrink `left` when a constraint is violated. Solves subarray/substring problems in **O(n)**.
91
What is the prefix sum technique?
Precompute cumulative sums: `prefix[i] = arr[0]+…+arr[i-1]`. Then `sum(i,j) = prefix[j+1] - prefix[i]` in **O(1)**.
92
What is Big-O notation?
An **upper bound** on the growth rate of an algorithm's resource usage as n → ∞; describes asymptotic worst-case behavior.
93
List the common Big-O complexities from fastest to slowest.
**O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ) < O(n!)**
94
What is the Big-O of a single for-loop over n elements? Of two nested for-loops?
Single loop → **O(n)**; two nested loops (each 0..n) → **O(n²)**.
95
How do you derive Big-O for recursive algorithms?
Set up a recurrence relation (e.g., T(n) = 2T(n/2) + O(n) for merge sort) and solve with the Master Theorem or substitution.
96
What is the Master Theorem used for?
Solves recurrences of the form T(n) = aT(n/b) + O(n^d) to give the time complexity of divide-and-conquer algorithms.
97
What is amortized O(1) push in a dynamic array?
Occasional resizes are O(n), but cost is spread over n pushes — each push costs **O(1) amortized** (aggregate method).
98
What are the time complexities for array: access, search, insert?
Access **O(1)**, Search **O(n)**, Insert **O(n)** (shifting required).
99
What are the time complexities for linked list: access, head insert/delete, search?
Access **O(n)**, Head insert/delete **O(1)**, Search **O(n)**.
100
What are the average and worst-case complexities for hash table operations?
Average **O(1)** for insert/lookup/delete; worst **O(n)** (all keys collide into one bucket).
101
What are BST operation complexities in average vs. worst case?
Average **O(log n)**; worst **O(n)** (degenerate/unbalanced tree — degrades to a linked list).
102
What are the complexities for a balanced BST (AVL or Red-Black tree)?
**O(log n) guaranteed** for insert, delete, search — self-balancing maintains height O(log n).
103
What are heap time complexities: insert, peek, extract-min?
Insert **O(log n)**, Peek **O(1)**, Extract-min **O(log n)**.
104
What is the difference between NP and NP-complete?
NP = problems whose solutions can be **verified** in polynomial time. NP-complete = NP problems to which **all NP problems reduce** in polynomial time.
105
Name three NP-complete problems.
**Boolean Satisfiability (SAT)**, **Traveling Salesman (decision version)**, **0/1 Knapsack**.
106
If a problem is NP-hard, what is the correct interview response?
Acknowledge it's intractable optimally; propose an **approximation algorithm**, **heuristic**, or **greedy approach** with bounded error.
107
How does a hash table work internally?
An **array of buckets**; a hash function maps keys to indices; collisions resolved by **chaining** (linked list per bucket) or **open addressing** (probing).
108
What are two collision resolution strategies in hash tables?
**Chaining**: linked list at each bucket. **Open addressing**: probe for the next free slot (linear, quadratic, or double hashing).
109
What is the BST property?
For every node: all values in the **left subtree < node < right subtree**.
110
What does inorder traversal of a BST produce?
Elements in **sorted ascending order**.
111
List the four tree traversal orders and their patterns.
**Inorder** (L→N→R), **Preorder** (N→L→R), **Postorder** (L→R→N), **Level-order** (BFS, row by row).
112
What is a Trie (prefix tree) and what is it used for?
A tree where each path from root represents a string prefix; used for **autocomplete**, **spell-check**, and IP routing.
113
What is the difference between a min-heap and a max-heap?
Min-heap: parent ≤ children → **root is minimum**. Max-heap: parent ≥ children → **root is maximum**.
114
What are three ways to represent a graph?
**Adjacency list** (space-efficient for sparse), **adjacency matrix** (O(1) edge lookup, dense graphs), **objects & pointers**.
115
When is an adjacency matrix preferred over an adjacency list?
When the graph is **dense** (many edges) or you need **O(1) edge existence** lookup.
116
What is a stack and its key operations?
LIFO structure; **push** (add to top), **pop** (remove from top), **peek** — all O(1).
117
What is a queue and its key operations?
FIFO structure; **enqueue** (add to back), **dequeue** (remove from front) — O(1) with doubly linked list or circular array.
118
What is a deque?
Double-ended queue; supports **O(1) insert/delete at both ends**. Useful for sliding window max/min.
119
What is the fast & slow pointer technique used for? (linked lists)
**Cycle detection** (Floyd's algorithm), finding the **middle node**, and finding the **cycle start**.
120
When do you use a monotonic stack?
When finding the **next/previous greater or smaller element**; e.g., "Largest Rectangle in Histogram", "Daily Temperatures".
121
How do you find the median of a data stream efficiently?
Two heaps: a **max-heap for lower half** + **min-heap for upper half**; balance sizes (differ by at most 1). Median = top of max-heap or average of both tops.
122
How do you solve "Top-K elements" efficiently?
Use a **min-heap of size K**; push each element, pop if size > K. Result = heap contents. **O(n log k)**.
123
How do you merge K sorted lists efficiently?
Use a **min-heap**; initially push the head of each list. Pop minimum → push its `next`. **O(N log k)** where N = total nodes.
124
What is the difference between a process and a thread? (OS)
A process has its **own memory space**; threads **share memory** within a process. Thread creation is faster and cheaper.
125
What is a mutex (lock)? (concurrency)
A synchronization primitive ensuring **mutual exclusion** — only one thread can hold the lock at a time.
126
What is a semaphore? (concurrency)
Counter-based primitive; **counting semaphore** allows up to N concurrent accesses; **binary semaphore** acts like a mutex.
127
What are the four Coffman conditions for deadlock?
**Mutual exclusion**, **Hold-and-wait**, **No preemption**, **Circular wait** — deadlock requires all four simultaneously.
128
What is a race condition? (concurrency)
When the outcome depends on the **non-deterministic ordering** of concurrent operations accessing shared state.
129
What is livelock? (concurrency)
Threads keep changing state in response to each other but make **no progress** — unlike deadlock where threads are blocked.
130
What is starvation? (concurrency)
A thread is perpetually denied access to a resource because **other threads continually take priority**.
131
Name four CPU scheduling algorithms.
**FIFO** (first-in, first-out), **Round Robin** (time slices), **Priority** (highest priority first), **Shortest Job First (SJF)**.
132
What is virtual memory? (OS)
An abstraction giving each process the illusion of a large contiguous address space; backed by physical RAM + disk via **paging**.
133
What is the difference between stack and heap memory?
**Stack**: automatic LIFO, fixed size, stores local vars/frames, fast. **Heap**: dynamic allocation, larger, managed by GC or programmer, slower.
134
What does horizontal scaling mean vs. vertical scaling?
**Horizontal**: add more machines (scale out). **Vertical**: upgrade existing machine with more CPU/RAM (scale up).
135
What is the CAP theorem?
A distributed system can guarantee at most **2 of 3**: **C**onsistency, **A**vailability, **P**artition tolerance.
136
What is cache invalidation and why is it hard?
Ensuring cached data stays in sync with the source of truth; hard because stale data causes bugs but aggressive invalidation defeats caching benefits.
137
What is the purpose of a message queue in distributed systems?
**Decouples producers and consumers**; enables async processing, buffering, durability, and retry on failure.
138
SQL vs. NoSQL — key trade-off?
**SQL**: structured schema, ACID transactions, relational joins, scales vertically. **NoSQL**: flexible schema, scales horizontally, typically eventual consistency.