LeetCode 1435: Create a Session Bar Chart

Database

Problem Description

Explanation

To create a session bar chart, we need to visualize the sessions over time in a horizontal bar chart format. Each session should be represented by a bar, and we need to ensure that the bars are displayed proportionally to their duration.

Algorithmic Idea

  1. Calculate the total duration of all sessions.
  2. Calculate the width of each bar based on the proportion of its duration to the total duration.
  3. Display the bars horizontally in a bar chart format.

Time Complexity

The time complexity of this solution is O(n) where n is the number of sessions.

Space Complexity

The space complexity of this solution is O(1) as we are not using any extra space proportional to the input size.

Solutions

class Solution {
    public void createSessionBarChart(int[] sessionDurations) {
        int totalDuration = 0;
        for (int duration : sessionDurations) {
            totalDuration += duration;
        }

        for (int duration : sessionDurations) {
            int barWidth = (int) ((duration / (double) totalDuration) * 100);
            for (int i = 0; i < barWidth; i++) {
                System.out.print("#");
            }
            System.out.println();
        }
    }
}

Loading editor...