💡
Seb's Whiteboard
  • 👨‍💻Welcome, I'm Sebastien St Vil
  • Extras
    • Gradient Descent
    • How I learned Java
    • Machine Learning by Andrew Ng
  • Projects
    • 📉Backtest Equity Trading with SMA Strategy
    • Wellington GA Lab
    • Stock analysis
    • 📈Time Series Regression-based Trading Strategy
  • Arrays & Strings
    • Best Time to Buy and Sell Stock II
    • Online Stock Span
    • Implement strStr()
    • 2Sum
    • 3Sum
    • 3Sum Closest
    • 4Sum II
    • Set Matrix Zeroes
    • Group Anagrams
    • Longest Substring Without Repeating Characters
    • Remove Duplicates from Sorted Array
    • Move Zeroes
    • Valid Sudoku
    • Rotate Image
    • First Unique Character in a String
    • Design a Circular Queue
    • Longest Common Prefix
  • Binary Tree
  • Second Minimum Node In a Binary Tree (671)
  • Design
  • LRU Cache
  • Min Stack (155)
  • Sorting & Searching
    • Merge Sorted Array (88)
    • First Bad Version
  • Math
    • Power of Three (326)
    • Power of Two (231)
    • Count Prime (204)
    • Roman to Integer (13)
    • Fizz Buzz (412)
    • Count-and-Say
  • Dynamic Programming
    • Pascal's Triangle (118)
  • Linked List
    • Copy List with Random Pointer
    • Remove Nth Node From End of List
    • Remove Duplicated from Sorted List II
  • Tips
    • Finding dups
  • Sliding Window
    • Subarray Product Less Than K
Powered by GitBook
On this page

Was this helpful?

  1. Math

Fizz Buzz (412)

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Approach1:

In this approach, we simply write the code as the problem states, solution should be clear and readable. The only caveat is that we need to check the condition that checks for the multiple of 3 and 5 first (can also be written as multiple of 15) before setting the other conditions for the multiple of 3 individually and then 5 because any number divisible by 15 is also divisbile by 3 or 5.

class Solution {
    public List<String> fizzBuzz(int n) {
        List<String> list = new ArrayList<>();
        
        for(int i = 1; i <= n; i++){
            if(i % 3 == 0 && i % 5 == 0){
                list.add("FizzBuzz");
            }
            else if(i % 5 == 0){
                list.add("Buzz");
            }
            else if(i % 3 == 0){
                list.add("Fizz");
            }
            else{
                list.add(i + "");
            }
        }
        return list;
    }
}

Complexity: O(N) time and O(N) space.

Approach2:

In a scenario where you would want to optimize the code to make it more concise and extendable, there's another approach that could be implemented and for that you'll use a Map.

  • Insert the encoding options inside a Map, with the Key being the number and the Value being the corresponding Word

  • I want to use a LinkedHashMap due to the insertion Order Property compared to a regular Hashmap which just stores the lements in a random order. (A TreeMap could also be used but only if you define the order of how you want to concat the words with a Lambda Comparator in it's constructor)

  • As we iterate thorugh each number from 1 to n, we check if that number has an encoding option by iterating trough the keys of the map.

class Solution {
    public List<String> fizzBuzz(int n) {
        if (n <= 0) {
            return new ArrayList();
        }
        Map<Integer, String> map = new LinkedHashMap<>(); 
        map.put(15, "FizzBuzz");
        map.put(3, "Fizz");
        map.put(5, "Buzz");
        
        // map.put(7, "Yuzz"); 
        // map.put(9, "Mozz"); add more encoding options here ... 
        List<String> numsStrs = new LinkedList();
        for (int i = 1; i <= n; i++) { 
            StringBuilder encoded = new StringBuilder();
            for (int num : map.keySet()) {
                if (i % num == 0){
                    encoded.append(map.get(num));
                    break;
                } 
            }
            numsStrs.add((encoded.length() == 0) ? String.valueOf(i) : encoded.toString());
        }
        return numsStrs;
    }
}

Complexity: O(N) time and O(N) space.

PreviousRoman to Integer (13)NextCount-and-Say

Last updated 4 years ago

Was this helpful?