🥑
Codding Problems Solutions
  • Introduction
  • CodeWars ⚔️
    • 🌝Beta
      • Count vowels
      • Who am I?
    • 🎒8 Kyu
      • Get the mean of an array
      • Multiply
      • SQL Basics: Mod
    • 🎁7 Kyu
      • 80's Kids #2: Help ALF Find His Spaceship
      • Complementary DNA
      • GROCERY STORE: Inventory
      • Get the Middle Character
      • Growth of a Population
      • Highest and Lowest
      • Indexed capitalization
      • Jaden Casing Strings
      • Moves in squared strings (I)
      • SQL with Harry Potter: Sorting Hat Comparators
      • SQL: Regex String to Table
      • Shortest Word
      • Sorted? yes? no? how?
      • String ends with?
      • Sum of odd numbers
      • Sum of the first nth term of Series
      • Two to One
      • What time is it?
    • 🎩6 Kyu
      • Are they the "same"?
      • Backspaces in string
      • Banker's Plan
      • Bouncing Balls
      • Count the smiley faces!
      • Counting Duplicates
      • Delete occurrences of an element if it occurs more than n times
      • Dubstep
      • Framed Reflection
      • Is a number prime?
      • Linked Lists - Length & Count
      • Lottery Ticket
      • Maze Runner
      • Mexican Wave
      • Number Format
      • Persistent Bugger.
      • Playing with digits
      • Replace With Alphabet Position
      • SQL Basics: Simple EXISTS
      • SQL Basics: Simple HAVING
      • SQL Basics: Simple IN
      • Statistics for an Athletic Association
      • The Deaf Rats of Hamelin
      • Tortoise racing
      • Unique In Order
      • Who likes it?
    • 🎯5 Kyu
      • Double Cola
      • Integers: Recreation One
      • Maximum subarray sum
      • Moving Zeros To The End
      • Pete, the baker
      • Pick peaks
      • Product of consecutive Fib numbers
      • Rot13
      • The Hunger Games - Zoo Disaster!
      • Using Window Functions To Get Top N per Group
      • Variadic Parameter Pack Count
    • 💍4 Kyu
      • Matrix Determinant
      • Memoized Log Cutting
      • Range Extraction
      • Roman Numerals Helper
      • Simple Fun #159: Middle Permutation
      • Strip Comments
      • Sum of Intervals
      • The observed PIN
      • Tuple sum
  • LeetCode 🍃
    • 👌Easy
      • Backspace String Compare
      • Binary Search
      • Binary Tree Tilt
      • Check If N and Its Double Exist
      • Climbing Stairs
      • Complement of Base 10 Integer
      • Consecutive Characters
      • Contains Duplicate
      • Convert Binary Number in a Linked List to Integer
      • Count and Say
      • Defanging an IP Address
      • Delete Node in a Linked List
      • Duplicate Zeros
      • Excel Sheet Column Number
      • Fibonacci Number
      • Find All Numbers Disappeared in an Array
      • Find Numbers with Even Number of Digits
      • Find the Difference
      • First Unique Character in a String
      • Fizz Buzz
      • Goat Latin
      • Height Checker
      • Implement strStr()
      • Intersection of Two Arrays II
      • Invert Binary Tree
      • Jewels and Stones
      • Kids With the Greatest Number of Candies
      • Length of Last Word
      • Longest Common Prefix
      • Longest Word in Dictionary
      • Max Consecutive Ones
      • Maximum Depth of Binary Tree
      • Merge Sorted Array
      • Merge Two Sorted Lists
      • Middle of the Linked List
      • Minimum Depth of Binary Tree
      • Move Zeroes
      • N-th Tribonacci Number
      • Number of 1 Bits
      • Number of Good Pairs
      • Number of Recent Calls
      • Palindrome Number
      • Pascal's Triangle II
      • Path Sum
      • Plus One
      • Power of Four
      • Power of Two
      • Remove Duplicates from Sorted Array
      • Remove Element
      • Replace Elements with Greatest Element on Right Side
      • Reverse Bits
      • Reverse Integer
      • Reverse String
      • Roman to Integer
      • Running Sum of 1d Array
      • Shuffle the Array
      • Single Number
      • Sort Array By Parity
      • Squares of a Sorted Array
      • Sum of Left Leaves
      • Sum of Root To Leaf Binary Numbers
      • Symmetric Tree
      • Tenth Line
      • Third Maximum Number
      • Transpose Matrix
      • Two Sum
      • Valid Anagram
      • Valid Mountain Array
      • Valid Parentheses
      • Word Pattern
      • XOR Operation in an Array
    • 👊Medium
      • All Elements in Two Binary Search Trees
      • Asteroid Collision
      • Binary Tree Inorder Traversal
      • Binary Tree Level Order Traversal
      • Binary Tree Postorder Traversal
      • Binary Tree Preorder Traversal
      • Bulls and Cows
      • Car Pooling
      • Combination Sum
      • Combination Sum III
      • Compare Version Numbers
      • Counting Bits
      • Course Schedule II
      • Design Linked List
      • Gas Station
      • House Robber
      • Image Overlap
      • Insert Interval
      • Insert into a Binary Search Tree
      • Insertion Sort List
      • K-diff Pairs in an Array
      • Kth Largest Element in an Array
      • Longest Substring Without Repeating Characters
      • Lowest Common Ancestor of a Binary Tree
      • Majority Element II
      • Maximum Difference Between Node and Ancestor
      • Maximum Product Subarray
      • Minimum Domino Rotations For Equal Row
      • Minimum Number of Arrows to Burst Balloons
      • Random Point in Non-overlapping Rectangles
      • Remove Covered Intervals
      • Rotate Array
      • Rotate Image
      • Rotate List
      • Rotting Oranges
      • Serialize and Deserialize BST
      • Sort List
      • String to Integer (atoi)
      • Teemo Attacking
      • Top K Frequent Elements
      • Valid Sudoku
    • 💪Hard
      • Median of Two Sorted Arrays
      • Parsing A Boolean Expression
      • Recover Binary Search Tree
      • Stone Game IV
Powered by GitBook
On this page
  • Sum of Intervals
  • Intervals
  • Overlapping Intervals
  • Examples:
  • Solutions

Was this helpful?

  1. CodeWars ⚔️
  2. 4 Kyu

Sum of Intervals

PreviousStrip CommentsNextThe observed PIN

Last updated 4 years ago

Was this helpful?

Write a function called sumIntervals/sum_intervals() that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once.

Intervals

Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example: [1, 5] is an interval from 1 to 5. The length of this interval is 4.

Overlapping Intervals

List containing overlapping intervals:

[
   [1,4],
   [7, 10],
   [3, 5]
]

The sum of the lengths of these intervals is 7. Since [1, 4] and [3, 5] overlap, we can treat the interval as [1, 5], which has a length of 4.

Examples:

sumIntervals( [
   [1,2],
   [6, 10],
   [11, 15]
] ); // => 9

sumIntervals( [
   [1,4],
   [7, 10],
   [3, 5]
] ); // => 7

sumIntervals( [
   [1,5],
   [10, 20],
   [1, 6],
   [16, 19],
   [5, 11]
] ); // => 19
// null argument
Interval.sumIntervals(null);  // => 0

// empty intervals
Interval.sumIntervals(new int[][]{});  // => 0
Interval.sumIntervals(new int[][]{2,2}, {5,5});  // => 0

// disjoined intervals
Interval.sumIntervals(new int[][]{
  {1,2},{3,5}
});  // => (2-1) + (5-3) = 3

// overlapping intervals
Interval.sumIntervals(new int[][]{
  {1,4},{3,6},{2,8}
});  // [1,8] => 7
// empty intervals
Intervals.SumIntervals(new (int, int)[]{ });  // => 0
Intervals.SumIntervals(new (int, int)[]{ (2, 2), (5, 5)});  // => 0

// disjoined intervals
Intervals.SumIntervals(new (int, int)[]{
  (1, 2), (3, 5)
});  // => (2-1) + (5-3) = 3

// overlapping intervals
Intervals.SumIntervals(new (int, int)[]{
  (1, 4), (3, 6), (2, 8)
});  // (1,8) => 7
sum_intervals( {
   {1,2},
   {6, 10},
   {11, 15}
} ); // => 9

sum_intervals( {
   {1,4},
   {7, 10},
   {3, 5}
} ); // => 7

sum_intervals( {
   {1,5},
   {10, 20},
   {1, 6},
   {16, 19},
   {5, 11}
} ); // => 19
sum_intervals((const struct interval[]){
   {1,2},
   {6, 10},
   {11, 15}
}, 3); /* => 9 */

sum_intervals((const struct interval[]){
   {1,4},
   {7, 10},
   {3, 5}
}, 3); /* => 7 */

sum_intervals((const struct interval[]){
   {1,5},
   {10, 20},
   {1, 6},
   {16, 19},
   {5, 11}
}, 5); /* => 19 */
v1:
    dd    1,2, \
          6,10, \
          11,15
v2:
    dd    1,4
    dd    7,10
    dd    3,5
v3:
    dd    1,5, 10,20, 1,6, 16,19, 5,11

    mov rdi, v1
    mov rsi, 3
    call sumintvls    ; EAX <- 9

    mov rdi, v2
    mov rsi, 3
    call sumintvls    ; EAX <- 7

    mov rdi, v3
    mov rsi, 5
    call sumintvls    ; EAX <- 19
(sum-intervals [ [1 5] [10 15] [-1 3] ]) ; => 11

(sum-intervals [ [1 5] ]) ; => 4
sumOfIntervals([[1, 5], [10, 15], [-1, 3]]) // => 11

sumOfIntervals([[1, 5]]) // => 4
sum_of_intervals([{1, 5}, {10, 15}, {-1, 3}]) # => 11

sum_of_intervals([{1, 5}]) # => 4
sum_of_intervals([{1, 5}, {10, 15}, {-1, 3}]) # => 11

sum_of_intervals([{1, 5}]) # => 4
sumOfIntervals([(1, 5}, (10, 15}, (-1, 3)]) -- => 11

sumOfIntervals([(1, 5)]) -- => 4
sumofintervals([(1, 5}, (10, 15}, (-1, 3)]) # => 11

sumofintervals([(1, 5)]) # => 4
sumOfIntervals([[1, 5], [10, 15], [-1, 3]]) // => 11

sumOfIntervals([[1, 5]]) // => 4
(sum-intervals (list (list -1 21) (list -59 -45))) ;; 36
(sum-intervals (list (list 1 5) (list 10 15) (list -1 3))) ;; 11
(sum-intervals (list (list 1 2) (list 6 10) (list 11 15))) ;; 36

Solutions

🐍 Python

def sum_of_intervals(intervals):
    for _ in range(3):
        valid_intervals = [list(intervals[0])]

        for n, itrl in enumerate(intervals[1:]):
            is_sub_interval = False
            for k, v_itrl in enumerate(valid_intervals):
                # [  (     ]  )
                if v_itrl[0] <= itrl[0] and v_itrl[1] >= itrl[0]:
                    is_sub_interval = True
                    if  itrl[1] > v_itrl[1]:
                        valid_intervals[k][1] = itrl[1]
                # (  [     )  ]
                elif v_itrl[1] >= itrl[1] and v_itrl[0] <= itrl[1]:
                    is_sub_interval = True
                    if  itrl[0] < v_itrl[0]:
                        valid_intervals[k][0] = itrl[0]

            if not is_sub_interval:
                valid_intervals.append(list(itrl))

            intervals=list(reversed(valid_intervals))    

    return sum(x[1]-x[0] for x in valid_intervals)
💍
Sum of Intervals