Java | 0 ms | O(1)* | Defines own generator (extends AbstractList<>)
Intuition\nThere is a repeating pattern with Fizzes and Buzzes every 15 elements. Also the problem description asks to return a List, rather then an array meani
# Intuition\nThere is a repeating pattern with Fizzes and Buzzes every 15 elements. Also the problem description asks to return a List<String>, rather then an array meaning we don\'t really have to generate all elements.\n\n# Approach\nImplement our own List type that returns correct string depending on index. Extending AbstractList is the easiest since we only need to define two methods.\n\nThe size method simply returns n.\n\nThe get method is our generator that takes advantage of repeated pattern. Switch seems more performant than dealing with multiple ifs.\n\n# Complexity\n- Time complexity: $$O(1)$$ --> returns generator instance that implements List<String>\n\n- Space complexity: $$O(1)$$ --> pattern matching w/o keeping whole sequence\n\n# Code\n```\nimport java.util.AbstractList;\nimport java.util.List;\n\nclass Solution {\n    public List<String> fizzBuzz(int n) {\n        return new AbstractList<>() {\n            @Override\n            public String get(int index) {\n                return switch (++index % 15) {\n                    case 0 -> "FizzBuzz";\n                    case 3, 6, 9, 12 -> "Fizz";\n                    case 5, 10 -> "Buzz";\n                    default -> String.valueOf(index);\n                };\n            }\n\n            @Override\n            public int size() {\n                return n;\n            }\n        };\n    }\n}\n```
['Java']