This repository includes all Python code for the book "Python Interview" and various coding interview problems.
All algorithm files follow a consistent numbering scheme: {category}-{number}_{algorithm_name}.py
Categories:
2-x: String and Array Problems3-x: String Manipulation4-x: Array Problems5-x: Greedy Algorithms6-x: Data Structures8-x: Linked Lists9-x: Trees12-x: Binary Search13-x: Two-Pointer Method14-x: Dynamic Programming15-x: Depth-First Search (DFS)16-x: Backtracking17-x: Breadth-First Search (BFS) and Graph Algorithms18-x: Union-Find19-x: Advanced Algorithms
Each algorithm includes detailed documentation in the demo/ folder:
- Demo Scripts: Step-by-step execution examples (
*_demo.py) - Markdown Documentation: Comprehensive explanations with:
- Problem description and key insights
- Detailed step-by-step examples
- Algorithm logic and pseudocode
- Complexity analysis
- Edge cases and common mistakes
- Visual representations and timelines
Example:
- Algorithm:
12-1_mySqrt.py - Documentation:
demo/12-1_mySqrt_output.md
This repository contains a complete Python implementation of the Super Streak counting problem, including all follow-up questions and optimizations.
The Super Streak problem involves counting consecutive gaming events that meet specific criteria:
- Streak Rules: A streak continues as long as events have the same
event_typeand the time gap between consecutive events is ≤ T seconds. - Super Streak Criteria: A streak qualifies as a "Super Streak" if:
- It contains at least N actions
- The total duration spans at least X seconds
count_super_streaks.py- Main implementation with all solutionscount_super_streaks_test.py- Comprehensive test casesdemo_super_streak.py- Interactive demonstrationcount_super_streaks.txt- Original problem statement
- Function:
count_super_streaks(events, N, T, X) - Time Complexity: O(n)
- Space Complexity: O(1)
- Algorithm: 2-pointer technique
- Function:
count_super_streaks_multiple_users(events, N, T, X) - Time Complexity: O(n)
- Space Complexity: O(n)
- Approach: Group events by user, then apply single-user algorithm
- Function:
count_super_streaks_optimized(events, N, T, X) - Time Complexity: O(n)
- Space Complexity: O(m) where m = number of unique users
- Approach: State management for each user
- Class:
SuperStreakTracker - Preprocessing: O(n)
- Query Time: O(log k) per query
- Feature: Binary search on sorted streak intervals
from count_super_streaks import Event, count_super_streaks
events = [
Event(101, "jump", 10),
Event(102, "jump", 18),
Event(301, "collect_coin", 98),
Event(302, "collect_coin", 105),
Event(303, "collect_coin", 112),
Event(304, "collect_coin", 122),
Event(305, "collect_coin", 131),
Event(306, "collect_coin", 140)
]
result = count_super_streaks(events, N=4, T=10, X=30)
print(f"Super streaks found: {result}") # Output: 1from count_super_streaks import MultiUserEvent, count_super_streaks_multiple_users
events = [
MultiUserEvent(1, 101, "jump", 10),
MultiUserEvent(1, 102, "jump", 15),
MultiUserEvent(2, 201, "crouch", 12),
# ... more events
]
result = count_super_streaks_multiple_users(events, N=3, T=10, X=20)
print(result) # Output: {1: 1, 2: 1}from count_super_streaks import SuperStreakTracker
tracker = SuperStreakTracker()
tracker.process_events(events, N=3, T=10, X=20)
# Count super streaks for user 1 in time range [25, 55]
count = tracker.count_streaks_in_range(1, 25, 55)
print(f"Super streaks in range: {count}")python3 count_super_streaks_test.pypython3 demo_super_streak.pypython3 count_super_streaks.pyThe main algorithm uses a two-pointer technique:
- Left pointer: Marks the start of a potential streak
- Right pointer: Extends the streak as long as conditions are met
- Streak validation: Check if completed streak meets super streak criteria
- Pointer advancement: Move to next potential streak start
- Only check for super streak criteria when a streak ends
- Handle edge case where the last streak continues until the end
- Efficiently process events without storing intermediate results (space optimization)
- Use binary search for fast time range queries
| Solution | Time Complexity | Space Complexity | Best Use Case |
|---|---|---|---|
| Main Solution | O(n) | O(1) | Single user analysis |
| Multiple Users | O(n) | O(n) | General multi-user scenarios |
| Space Optimized | O(n) | O(m) | When events >> users |
| Time Range Queries | O(log k) per query | O(n) preprocessing | Frequent time-based queries |
Where:
- n = total number of events
- m = number of unique users
- k = number of super streaks per user
This solution can be applied to:
- Gaming analytics and player behavior analysis
- User engagement tracking
- Performance monitoring systems
- Time-series data analysis
- Activity pattern recognition
- Python 3.6+
- No external dependencies required (uses only standard library)
Each algorithm file can be run directly:
python3 12-1_mySqrt.py
python3 17-2_curriculum.py
# etc.Detailed documentation for each algorithm is available in the demo/ folder:
# View markdown documentation
cat demo/12-1_mySqrt_output.md
cat demo/17-2_curriculum_output.md
# etc.When adding new algorithms:
- Follow the numbering scheme:
{category}-{number}_{algorithm_name}.py - Include a
main()function with test cases - Add detailed comments explaining the algorithm
- Create documentation in the
demo/folder if needed
12-1_mySqrt.py- Integer square root12-2_search_rotated_array.py- Search in rotated sorted array12-3_search_intervals.py- Interval search with range table
13-1_sparse_vector_product.py- Dot product of sparse vectors13-2_minimum_window_substring.py- Minimum window substring13-3_interval_intersection.py- Interval intersection13-4_maximum_consecutive_ones.py- Maximum consecutive ones with K flips13-5_find_anagrams.py- Find all anagrams
14-1_maxProfit.py- Best time to buy and sell stock14-2_coin_change.py- Coin change problem14-3_decoding_ways.py- Decode ways
15-1_pacific_atlantic_currents.py- Pacific Atlantic water flow15-2_predict_winner.py- Predict the winner (minimax)15-3_expression_add_operator.py- Expression add operators
16-1_sudoku_solver.py- Sudoku solver16-2_robot_vacuum.py- Robot room cleaner
17-1_walls_and_gates.py- Multi-source BFS for shortest distances17-2_curriculum.py- Course schedule (topological sort)17-3_bus_routes.py- Minimum buses to destination17-4_isBipartite.py- Bipartite graph detection17-5_word_ladder_II.py- Word ladder II (all shortest paths)
18-1_union_find.py- Union-Find data structure
19-1_FileSystem.py- File system size calculation (DFS)19-2_longest_significant_chain.py- Longest word chain19-3_NumbCircles.py- Circle groups (connected components)
2-2_binaryAddition.py- Binary addition2-3_random_indexing.py- Random indexing2-4_next_permuation.py- Next permutation2-5_valid_decimal_numbers.py- Valid decimal numbers
- String Manipulation (3-x): Minimum remove parentheses
- Array Problems (4-x): Shortest array larger than K
- Greedy Algorithms (5-x): Minimum cost to hire, traffic light
- Data Structures (6-x): Subarrays sum to K, LRU cache
- Linked Lists (8-x): Cycle detection, intersection, deep copy
- Trees (9-x): Lowest common ancestor, serialize/deserialize
-
Comprehensive Solutions: Each algorithm includes:
- Clean, well-commented code
- Multiple test cases
- Main function with examples
- Detailed documentation
-
Educational Focus:
- Step-by-step explanations
- Complexity analysis
- Visual representations
- Common mistakes and edge cases
-
Production Ready:
- Type hints
- Error handling
- Edge case coverage
- Performance optimizations
This implementation is provided for educational and interview preparation purposes.