{ "data": { "question": { "questionId": "2357", "questionFrontendId": "2276", "boundTopicId": null, "title": "Count Integers in Intervals", "titleSlug": "count-integers-in-intervals", "content": "

Given an empty set of intervals, implement a data structure that can:

\n\n\n\n

Implement the CountIntervals class:

\n\n\n\n

Note that an interval [left, right] denotes all the integers x where left <= x <= right.

\n\n

 

\n

Example 1:

\n\n
\nInput\n["CountIntervals", "add", "add", "count", "add", "count"]\n[[], [2, 3], [7, 10], [], [5, 8], []]\nOutput\n[null, null, null, 6, null, 8]\n\nExplanation\nCountIntervals countIntervals = new CountIntervals(); // initialize the object with an empty set of intervals. \ncountIntervals.add(2, 3);  // add [2, 3] to the set of intervals.\ncountIntervals.add(7, 10); // add [7, 10] to the set of intervals.\ncountIntervals.count();    // return 6\n                           // the integers 2 and 3 are present in the interval [2, 3].\n                           // the integers 7, 8, 9, and 10 are present in the interval [7, 10].\ncountIntervals.add(5, 8);  // add [5, 8] to the set of intervals.\ncountIntervals.count();    // return 8\n                           // the integers 2 and 3 are present in the interval [2, 3].\n                           // the integers 5 and 6 are present in the interval [5, 8].\n                           // the integers 7 and 8 are present in the intervals [5, 8] and [7, 10].\n                           // the integers 9 and 10 are present in the interval [7, 10].\n
\n\n

 

\n

Constraints:

\n\n\n", "translatedTitle": null, "translatedContent": null, "isPaidOnly": false, "difficulty": "Hard", "likes": 530, "dislikes": 55, "isLiked": null, "similarQuestions": "[{\"title\": \"Merge Intervals\", \"titleSlug\": \"merge-intervals\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Insert Interval\", \"titleSlug\": \"insert-interval\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Data Stream as Disjoint Intervals\", \"titleSlug\": \"data-stream-as-disjoint-intervals\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"My Calendar III\", \"titleSlug\": \"my-calendar-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "exampleTestcases": "[\"CountIntervals\",\"add\",\"add\",\"count\",\"add\",\"count\"]\n[[],[2,3],[7,10],[],[5,8],[]]", "categoryTitle": "Algorithms", "contributors": [], "topicTags": [ { "name": "Design", "slug": "design", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Segment Tree", "slug": "segment-tree", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Ordered Set", "slug": "ordered-set", "translatedName": null, "__typename": "TopicTagNode" } ], "companyTagStats": null, "codeSnippets": [ { "lang": "C++", "langSlug": "cpp", "code": "class CountIntervals {\npublic:\n CountIntervals() {\n \n }\n \n void add(int left, int right) {\n \n }\n \n int count() {\n \n }\n};\n\n/**\n * Your CountIntervals object will be instantiated and called as such:\n * CountIntervals* obj = new CountIntervals();\n * obj->add(left,right);\n * int param_2 = obj->count();\n */", "__typename": "CodeSnippetNode" }, { "lang": "Java", "langSlug": "java", "code": "class CountIntervals {\n\n public CountIntervals() {\n \n }\n \n public void add(int left, int right) {\n \n }\n \n public int count() {\n \n }\n}\n\n/**\n * Your CountIntervals object will be instantiated and called as such:\n * CountIntervals obj = new CountIntervals();\n * obj.add(left,right);\n * int param_2 = obj.count();\n */", "__typename": "CodeSnippetNode" }, { "lang": "Python", "langSlug": "python", "code": "class CountIntervals(object):\n\n def __init__(self):\n \n\n def add(self, left, right):\n \"\"\"\n :type left: int\n :type right: int\n :rtype: None\n \"\"\"\n \n\n def count(self):\n \"\"\"\n :rtype: int\n \"\"\"\n \n\n\n# Your CountIntervals object will be instantiated and called as such:\n# obj = CountIntervals()\n# obj.add(left,right)\n# param_2 = obj.count()", "__typename": "CodeSnippetNode" }, { "lang": "Python3", "langSlug": "python3", "code": "class CountIntervals:\n\n def __init__(self):\n \n\n def add(self, left: int, right: int) -> None:\n \n\n def count(self) -> int:\n \n\n\n# Your CountIntervals object will be instantiated and called as such:\n# obj = CountIntervals()\n# obj.add(left,right)\n# param_2 = obj.count()", "__typename": "CodeSnippetNode" }, { "lang": "C", "langSlug": "c", "code": "\n\n\ntypedef struct {\n \n} CountIntervals;\n\n\nCountIntervals* countIntervalsCreate() {\n \n}\n\nvoid countIntervalsAdd(CountIntervals* obj, int left, int right) {\n \n}\n\nint countIntervalsCount(CountIntervals* obj) {\n \n}\n\nvoid countIntervalsFree(CountIntervals* obj) {\n \n}\n\n/**\n * Your CountIntervals struct will be instantiated and called as such:\n * CountIntervals* obj = countIntervalsCreate();\n * countIntervalsAdd(obj, left, right);\n \n * int param_2 = countIntervalsCount(obj);\n \n * countIntervalsFree(obj);\n*/", "__typename": "CodeSnippetNode" }, { "lang": "C#", "langSlug": "csharp", "code": "public class CountIntervals {\n\n public CountIntervals() {\n \n }\n \n public void Add(int left, int right) {\n \n }\n \n public int Count() {\n \n }\n}\n\n/**\n * Your CountIntervals object will be instantiated and called as such:\n * CountIntervals obj = new CountIntervals();\n * obj.Add(left,right);\n * int param_2 = obj.Count();\n */", "__typename": "CodeSnippetNode" }, { "lang": "JavaScript", "langSlug": "javascript", "code": "\nvar CountIntervals = function() {\n \n};\n\n/** \n * @param {number} left \n * @param {number} right\n * @return {void}\n */\nCountIntervals.prototype.add = function(left, right) {\n \n};\n\n/**\n * @return {number}\n */\nCountIntervals.prototype.count = function() {\n \n};\n\n/** \n * Your CountIntervals object will be instantiated and called as such:\n * var obj = new CountIntervals()\n * obj.add(left,right)\n * var param_2 = obj.count()\n */", "__typename": "CodeSnippetNode" }, { "lang": "TypeScript", "langSlug": "typescript", "code": "class CountIntervals {\n constructor() {\n \n }\n\n add(left: number, right: number): void {\n \n }\n\n count(): number {\n \n }\n}\n\n/**\n * Your CountIntervals object will be instantiated and called as such:\n * var obj = new CountIntervals()\n * obj.add(left,right)\n * var param_2 = obj.count()\n */", "__typename": "CodeSnippetNode" }, { "lang": "PHP", "langSlug": "php", "code": "class CountIntervals {\n /**\n */\n function __construct() {\n \n }\n \n /**\n * @param Integer $left\n * @param Integer $right\n * @return NULL\n */\n function add($left, $right) {\n \n }\n \n /**\n * @return Integer\n */\n function count() {\n \n }\n}\n\n/**\n * Your CountIntervals object will be instantiated and called as such:\n * $obj = CountIntervals();\n * $obj->add($left, $right);\n * $ret_2 = $obj->count();\n */", "__typename": "CodeSnippetNode" }, { "lang": "Swift", "langSlug": "swift", "code": "\nclass CountIntervals {\n\n init() {\n \n }\n \n func add(_ left: Int, _ right: Int) {\n \n }\n \n func count() -> Int {\n \n }\n}\n\n/**\n * Your CountIntervals object will be instantiated and called as such:\n * let obj = CountIntervals()\n * obj.add(left, right)\n * let ret_2: Int = obj.count()\n */", "__typename": "CodeSnippetNode" }, { "lang": "Kotlin", "langSlug": "kotlin", "code": "class CountIntervals() {\n\n fun add(left: Int, right: Int) {\n \n }\n\n fun count(): Int {\n \n }\n\n}\n\n/**\n * Your CountIntervals object will be instantiated and called as such:\n * var obj = CountIntervals()\n * obj.add(left,right)\n * var param_2 = obj.count()\n */", "__typename": "CodeSnippetNode" }, { "lang": "Dart", "langSlug": "dart", "code": "class CountIntervals {\n\n CountIntervals() {\n \n }\n \n void add(int left, int right) {\n \n }\n \n int count() {\n \n }\n}\n\n/**\n * Your CountIntervals object will be instantiated and called as such:\n * CountIntervals obj = CountIntervals();\n * obj.add(left,right);\n * int param2 = obj.count();\n */", "__typename": "CodeSnippetNode" }, { "lang": "Go", "langSlug": "golang", "code": "type CountIntervals struct {\n \n}\n\n\nfunc Constructor() CountIntervals {\n \n}\n\n\nfunc (this *CountIntervals) Add(left int, right int) {\n \n}\n\n\nfunc (this *CountIntervals) Count() int {\n \n}\n\n\n/**\n * Your CountIntervals object will be instantiated and called as such:\n * obj := Constructor();\n * obj.Add(left,right);\n * param_2 := obj.Count();\n */", "__typename": "CodeSnippetNode" }, { "lang": "Ruby", "langSlug": "ruby", "code": "class CountIntervals\n def initialize()\n \n end\n\n\n=begin\n :type left: Integer\n :type right: Integer\n :rtype: Void\n=end\n def add(left, right)\n \n end\n\n\n=begin\n :rtype: Integer\n=end\n def count()\n \n end\n\n\nend\n\n# Your CountIntervals object will be instantiated and called as such:\n# obj = CountIntervals.new()\n# obj.add(left, right)\n# param_2 = obj.count()", "__typename": "CodeSnippetNode" }, { "lang": "Scala", "langSlug": "scala", "code": "class CountIntervals() {\n\n def add(left: Int, right: Int) {\n \n }\n\n def count(): Int = {\n \n }\n\n}\n\n/**\n * Your CountIntervals object will be instantiated and called as such:\n * var obj = new CountIntervals()\n * obj.add(left,right)\n * var param_2 = obj.count()\n */", "__typename": "CodeSnippetNode" }, { "lang": "Rust", "langSlug": "rust", "code": "struct CountIntervals {\n\n}\n\n\n/** \n * `&self` means the method takes an immutable reference.\n * If you need a mutable reference, change it to `&mut self` instead.\n */\nimpl CountIntervals {\n\n fn new() -> Self {\n \n }\n \n fn add(&self, left: i32, right: i32) {\n \n }\n \n fn count(&self) -> i32 {\n \n }\n}\n\n/**\n * Your CountIntervals object will be instantiated and called as such:\n * let obj = CountIntervals::new();\n * obj.add(left, right);\n * let ret_2: i32 = obj.count();\n */", "__typename": "CodeSnippetNode" }, { "lang": "Racket", "langSlug": "racket", "code": "(define count-intervals%\n (class object%\n (super-new)\n \n (init-field)\n \n ; add : exact-integer? exact-integer? -> void?\n (define/public (add left right)\n )\n ; count : -> exact-integer?\n (define/public (count)\n )))\n\n;; Your count-intervals% object will be instantiated and called as such:\n;; (define obj (new count-intervals%))\n;; (send obj add left right)\n;; (define param_2 (send obj count))", "__typename": "CodeSnippetNode" }, { "lang": "Erlang", "langSlug": "erlang", "code": "-spec count_intervals_init_() -> any().\ncount_intervals_init_() ->\n .\n\n-spec count_intervals_add(Left :: integer(), Right :: integer()) -> any().\ncount_intervals_add(Left, Right) ->\n .\n\n-spec count_intervals_count() -> integer().\ncount_intervals_count() ->\n .\n\n\n%% Your functions will be called as such:\n%% count_intervals_init_(),\n%% count_intervals_add(Left, Right),\n%% Param_2 = count_intervals_count(),\n\n%% count_intervals_init_ will be called before every test case, in which you can do some necessary initializations.", "__typename": "CodeSnippetNode" }, { "lang": "Elixir", "langSlug": "elixir", "code": "defmodule CountIntervals do\n @spec init_() :: any\n def init_() do\n \n end\n\n @spec add(left :: integer, right :: integer) :: any\n def add(left, right) do\n \n end\n\n @spec count() :: integer\n def count() do\n \n end\nend\n\n# Your functions will be called as such:\n# CountIntervals.init_()\n# CountIntervals.add(left, right)\n# param_2 = CountIntervals.count()\n\n# CountIntervals.init_ will be called before every test case, in which you can do some necessary initializations.", "__typename": "CodeSnippetNode" } ], "stats": "{\"totalAccepted\": \"15.3K\", \"totalSubmission\": \"44.5K\", \"totalAcceptedRaw\": 15342, \"totalSubmissionRaw\": 44452, \"acRate\": \"34.5%\"}", "hints": [ "How can you efficiently add intervals to the set of intervals? Can a data structure like a Binary Search Tree help?", "How can you ensure that the intervals present in the set are non-overlapping? Try merging the overlapping intervals whenever a new interval is added.", "How can you update the count of integers present in at least one interval when a new interval is added to the set?" ], "solution": null, "status": null, "sampleTestCase": "[\"CountIntervals\",\"add\",\"add\",\"count\",\"add\",\"count\"]\n[[],[2,3],[7,10],[],[5,8],[]]", "metaData": "{\n \"classname\": \"CountIntervals\",\n \"constructor\": {\n \"params\": []\n },\n \"methods\": [\n {\n \"params\": [\n {\n \"type\": \"integer\",\n \"name\": \"left\"\n },\n {\n \"type\": \"integer\",\n \"name\": \"right\"\n }\n ],\n \"name\": \"add\",\n \"return\": {\n \"type\": \"void\"\n }\n },\n {\n \"params\": [],\n \"name\": \"count\",\n \"return\": {\n \"type\": \"integer\"\n }\n }\n ],\n \"return\": {\n \"type\": \"boolean\"\n },\n \"systemdesign\": true\n}", "judgerAvailable": true, "judgeType": "large", "mysqlSchemas": [], "enableRunCode": true, "enableTestMode": false, "enableDebugger": true, "envInfo": "{\"cpp\": [\"C++\", \"

Compiled with clang 11 using the latest C++ 20 standard.

\\r\\n\\r\\n

Your code is compiled with level two optimization (-O2). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\"], \"java\": [\"Java\", \"

OpenJDK 17. Java 8 features such as lambda expressions and stream API can be used.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n

Includes Pair class from https://docs.oracle.com/javase/8/javafx/api/javafx/util/Pair.html.

\"], \"python\": [\"Python\", \"

Python 2.7.12.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\\r\\n\\r\\n

Note that Python 2.7 will not be maintained past 2020. For the latest Python, please choose Python3 instead.

\"], \"c\": [\"C\", \"

Compiled with gcc 8.2 using the gnu11 standard.

\\r\\n\\r\\n

Your code is compiled with level one optimization (-O1). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n\\r\\n

For hash table operations, you may use uthash. \\\"uthash.h\\\" is included by default. Below are some examples:

\\r\\n\\r\\n

1. Adding an item to a hash.\\r\\n

\\r\\nstruct hash_entry {\\r\\n    int id;            /* we'll use this field as the key */\\r\\n    char name[10];\\r\\n    UT_hash_handle hh; /* makes this structure hashable */\\r\\n};\\r\\n\\r\\nstruct hash_entry *users = NULL;\\r\\n\\r\\nvoid add_user(struct hash_entry *s) {\\r\\n    HASH_ADD_INT(users, id, s);\\r\\n}\\r\\n
\\r\\n

\\r\\n\\r\\n

2. Looking up an item in a hash:\\r\\n

\\r\\nstruct hash_entry *find_user(int user_id) {\\r\\n    struct hash_entry *s;\\r\\n    HASH_FIND_INT(users, &user_id, s);\\r\\n    return s;\\r\\n}\\r\\n
\\r\\n

\\r\\n\\r\\n

3. Deleting an item in a hash:\\r\\n

\\r\\nvoid delete_user(struct hash_entry *user) {\\r\\n    HASH_DEL(users, user);  \\r\\n}\\r\\n
\\r\\n

\"], \"csharp\": [\"C#\", \"

C# 10 with .NET 6 runtime

\"], \"javascript\": [\"JavaScript\", \"

Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES6 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\\r\\n\\r\\n

For Priority Queue / Queue data structures, you may use 5.3.0 version of datastructures-js/priority-queue and 4.2.1 version of datastructures-js/queue.

\"], \"ruby\": [\"Ruby\", \"

Ruby 3.1

\\r\\n\\r\\n

Some common data structure implementations are provided in the Algorithms module: https://www.rubydoc.info/github/kanwei/algorithms/Algorithms

\"], \"swift\": [\"Swift\", \"

Swift 5.5.2.

\"], \"golang\": [\"Go\", \"

Go 1.21

\\r\\n

Support https://godoc.org/github.com/emirpasic/gods@v1.18.1 library.

\"], \"python3\": [\"Python3\", \"

Python 3.10.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\"], \"scala\": [\"Scala\", \"

Scala 2.13.7.

\"], \"kotlin\": [\"Kotlin\", \"

Kotlin 1.9.0.

\"], \"rust\": [\"Rust\", \"

Rust 1.58.1

\\r\\n\\r\\n

Supports rand v0.6\\u00a0from crates.io

\"], \"php\": [\"PHP\", \"

PHP 8.1.

\\r\\n

With bcmath module

\"], \"typescript\": [\"Typescript\", \"

TypeScript 5.1.6, Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES2022 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\"], \"racket\": [\"Racket\", \"

Run with Racket 8.3.

\"], \"erlang\": [\"Erlang\", \"Erlang/OTP 25.0\"], \"elixir\": [\"Elixir\", \"Elixir 1.13.4 with Erlang/OTP 25.0\"], \"dart\": [\"Dart\", \"

Dart 2.17.3

\\r\\n\\r\\n

Your code will be run directly without compiling

\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }