Skip to content

Conversation

phuoc-nguyenhuu
Copy link

🚀 Problem 1: Three Unique Implementations of Sum to N 🚀

Implementation explanation

1. sum_to_n_a - Iterative Approach (For Loop)

Approach: Classic iterative solution using a for loop

  • Time Complexity: O(n)
  • Space Complexity: O(1)

Pros:

  • Easy to understand and debug
  • Memory efficient (constant space)
  • No risk of stack overflow
  • Predictable performance

Cons:

  • Linear time complexity
  • Requires n iterations for computation

2. sum_to_n_b - Mathematical Formula Approach

Approach: Direct calculation using the arithmetic series formula n * (n + 1) / 2

  • Time Complexity: O(1)
  • Space Complexity: O(1)

Pros:

  • Constant time complexity - most efficient
  • Uses mathematical insight (Gauss's formula)
  • Minimal computational overhead
  • Scales perfectly regardless of input size

Cons:

  • Requires mathematical knowledge to understand
  • Potential for integer overflow with very large numbers (though mitigated by input validation)

3. sum_to_n_c - Recursive Approach

Approach: Recursive solution with base case

  • Time Complexity: O(n)
  • Space Complexity: O(n) - due to call stack

Pros:

  • Elegant and mathematically intuitive
  • Demonstrates functional programming concepts
  • Self-documenting (mirrors the mathematical definition)

Cons:

  • Risk of stack overflow for large inputs
  • Higher memory usage due to call stack
  • Generally slower due to function call overhead

Input Validation & Edge Cases

Robust Input Validation

Your valid_input() function ensures:

  • Input is an integer (using n % 1 !== 0)
  • Input doesn't exceed Number.MAX_SAFE_INTEGER
  • Throws descriptive error for invalid inputs

Edge Case Handling

All implementations properly handle:

  • n = 0: Returns 0 (correct mathematical result)
  • n < 0: Returns 0 (sensible default for negative inputs)
  • Non-integers: Throws validation error
  • Overflow risk: Prevented by input validation

Test Coverage

Your test suite comprehensively covers:

  • Input validation (non-integers, overflow)
  • Edge cases (zero, negative numbers)
  • Correct functionality (sum_to_n(5) = 15)
  • Consistent behavior across all three implementations

🚀 Problem 2 🚀

Currency Swap Form

Project Overview

This is a React + TypeScript + Vite application that implements a currency swap form allowing users to exchange one cryptocurrency for another. The project demonstrates modern frontend development practices with a clean, responsive UI.

Tech Stack

Core Technologies

  • React 19 with TypeScript for type safety
  • Vite as the build tool (bonus requirement fulfilled!)
  • Tailwind CSS v4 for styling with modern design system
  • Zustand for lightweight state management
  • TanStack Query for server state management and caching
  • Shadcn UI components for accessible UI primitives

Implemented Features

1. Real-time Currency Data

  • Fetches live prices from https://interview.switcheo.com/prices.json
  • Filters out currencies without prices
  • Removes duplicate currencies
  • Uses TanStack Query for caching and error handling

2. Interactive Swap Interface

  • Dual Currency Fields: From/To currency selection with amount inputs
  • Token Icons: Displays SVG icons for each cryptocurrency from /public/tokens/
  • Swap Button: Animated button with rotation effect to swap currencies
  • Real-time Exchange Rate: Shows current conversion rate between selected currencies

3. Smart Calculations

  • Bidirectional Updates: Changing amount in either field updates the other automatically
  • Precise Exchange Rates: Uses actual price data for accurate conversions
  • Input Validation: Prevents negative numbers, limits decimal precision to 8 places

4. State Management

  • Zustand Store: Manages fromCurrency, toCurrency, and swap operations
  • Reactive Updates: UI automatically updates when state changes
  • Type Safety: Full TypeScript coverage for all state operations

5. User Experience

  • Loading States: Shows spinner while fetching currency data
  • Error Handling: Displays error messages if API fails
  • Responsive Design: Works on mobile, tablet, and desktop
  • Smooth Animations: Fade-in effects and button hover animations
  • Accessibility: Uses Radix UI for keyboard navigation and screen readers

Strengths of Current Implementation

  • Modern React Patterns: Uses hooks, functional components, and TypeScript
  • Performance Optimized: TanStack Query caching, efficient re-renders
  • Accessible: Radix UI components ensure keyboard navigation and screen reader support
  • Type Safe: Comprehensive TypeScript coverage prevents runtime errors
  • Maintainable: Clean separation of concerns, modular component structure
  • Responsive: Works across all device sizes
  • Professional UI: Polished design with smooth animations

🚀 Problem 3🚀

Critical Issues

  1. Undefined Variable Reference: lhsPriority is used but never defined (line in filter function). This will cause a runtime error.

  2. Incorrect Type Usage: sortedBalances is typed as WalletBalance[] but used as FormattedWalletBalance[] in the rows mapping.

  3. Missing blockchain Property: The WalletBalance interface lacks a blockchain property that's used throughout the code.

Performance Anti-patterns

  1. Inefficient useMemo Dependencies: The sortedBalances useMemo includes prices in dependencies but doesn't use prices in the computation, causing unnecessary recalculations.

  2. Double Array Processing: formattedBalances is computed but never used, while sortedBalances is processed again in the rows mapping - wasteful double iteration.

  3. Missing Memoization: formattedBalances and rows aren't memoized, causing recalculation on every render.

  4. Inefficient Key Usage: Using array index as React key instead of a stable unique identifier can cause rendering issues and poor performance.

Logic Issues

  1. Inverted Filter Logic: The filter condition if (lhsPriority > -99) then if (balance.amount <= 0) return true keeps zero/negative balances, which is likely unintended.

  2. Incomplete Sort Comparison: The sort function doesn't handle the case where priorities are equal, potentially causing unstable sorting.

  3. Any Type Usage: getPriority parameter uses any type instead of a proper string type.

Code Quality Issues

  1. Empty Interface: Props extends BoxProps but adds nothing - could directly use BoxProps.

  2. Redundant Destructuring: (props: Props) then immediate destructuring is verbose.

Refactored Version

  1. Fixed undefined variable by using consistent variable names
  2. Added missing blockchain property to WalletBalance interface
  3. Combined filter/sort/map operations into single memoized computation
  4. Corrected filter logic to keep positive amounts with valid priorities
  5. Added stable sort with currency fallback for consistent ordering
  6. Memoized expensive computations to prevent unnecessary recalculations
  7. Used meaningful React keys instead of array indices
  8. Proper TypeScript typing throughout
  9. Removed unused formattedBalances variable
  10. Fixed dependency arrays in useMemo hooks
  11. Added useCallback for getPriority to prevent function recreation

@phuoc-nguyenhuu phuoc-nguyenhuu changed the title complete code challenge [FE] - Code Challenge - Nguyen Huu Phuoc Aug 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants