Search in sources :

Example 1 with Interval

use of org.hypertrace.gateway.service.v1.common.Interval in project leetcode-practice by snehasishroy.

the class EmployeeFreeTime method employeeFreeTimeUsingLineSweep.

/**
 * Approach: Prefix sum, Range Interval Problem, Line sweep algorithm by incrementing/decrementing a counter similar to {@link MeetingsRoom2}
 * {@link RemoveInterval}
 * <p>
 * I have to see the hint to implement the problem, Initially I was thinking of maintaining a list of free time for each employee and then
 * gradually comparing each employees free time to filter the common free time for all of them, it was a very complicated implementation.
 * TimeComplexity: nlogn, n is the total number of intervals
 * <p>
 * RunTime can be reduced if you use priority queue and push all the intervals to pq, and merge overlapping intervals.
 * Check if the previous interval and current interval are disjoint, if yes, the gap is the free interval
 * Refer to the priority queue solution in {@link IntervalListIntersections}
 *
 * {@link DescribeThePainting} {@link RangeAddition2}
 */
public List<Interval> employeeFreeTimeUsingLineSweep(List<List<Interval>> schedule) {
    // mapping of time -> counter (+1, -1)
    TreeMap<Integer, Integer> map = new TreeMap<>();
    for (List<Interval> intervals : schedule) {
        for (Interval interval : intervals) {
            map.put(interval.start, map.getOrDefault(interval.start, 0) + 1);
            map.put(interval.end, map.getOrDefault(interval.end, 0) - 1);
        }
    }
    ArrayList<Interval> result = new ArrayList<>();
    int start = -1, runningCounter = 0;
    for (Map.Entry<Integer, Integer> entrySet : map.entrySet()) {
        if (start != -1) {
            // if start of free time has been identified, this represent the end of common free time
            // all good things must come to an end
            result.add(new Interval(start, entrySet.getKey()));
            start = -1;
        }
        runningCounter += entrySet.getValue();
        if (runningCounter == 0) {
            // running counter of 0 indicates that no one is working at this time, so everyone is free, need to mark the start of the free time
            start = entrySet.getKey();
        }
    }
    return result;
}
Also used : ArrayList(java.util.ArrayList) TreeMap(java.util.TreeMap) TreeMap(java.util.TreeMap) Map(java.util.Map) Interval(common.Interval)

Example 2 with Interval

use of org.hypertrace.gateway.service.v1.common.Interval in project leetcode-practice by snehasishroy.

the class EraseNonOverlappingIntervals method eraseOverlapIntervals.

/**
 * My initial greedy approach: Idea is to start similar to {@link MergeIntervals} and always try to pick smallest interval
 * <pre>
 * 1-----------------10
 *     4---6
 * </pre>
 * Pick 4-6 instead of 1-10 as picking a smaller interval can lead to picking more non-overlapping intervals
 * If you pick a bigger range, no way you can pick more non-overlapping intervals
 */
public int eraseOverlapIntervals(int[][] intervals) {
    int n = intervals.length;
    if (n == 0) {
        return 0;
    }
    Interval[] input = new Interval[intervals.length];
    for (int i = 0; i < n; i++) {
        input[i] = new Interval(intervals[i][0], intervals[i][1]);
    }
    // sort by start
    Arrays.sort(input, Comparator.comparingInt(o -> o.start));
    // Result will store all the non-overlapping intervals
    Interval[] result = new Interval[n];
    int index = 0;
    result[index++] = input[0];
    for (int i = 1; i < n; i++) {
        if (input[i].start < result[index - 1].end && input[i].end < result[index - 1].end) {
            // if this interval is smaller than the last interval i.e. lies completely within the previous interval
            // replace the last interval with this interval in order to pick more non-overlapping intervals
            result[index - 1] = input[i];
        } else if (input[i].start >= result[index - 1].end) {
            // non-overlapping interval, just add to the result
            result[index++] = input[i];
        }
    }
    // Total intervals - non-overlapping intervals will give overlapping intervals
    return n - index;
}
Also used : Arrays(java.util.Arrays) Interval(common.Interval) Comparator(java.util.Comparator) Interval(common.Interval)

Example 3 with Interval

use of org.hypertrace.gateway.service.v1.common.Interval in project gateway-service by hypertrace.

the class TimeAggregationsRequestHandler method getRequestOrderByExpressions.

/**
 * Need to add the interval start timer Order By expression so that after we get the results from
 * Query Service, we can sort by this column.
 *
 * @param request
 * @return
 */
@Override
public List<OrderByExpression> getRequestOrderByExpressions(ExploreRequest request) {
    List<OrderByExpression> existingOrderBys = super.getRequestOrderByExpressions(request);
    List<OrderByExpression> resolvedOrderBys = new ArrayList<>();
    if (!this.containsIntervalOrdering(existingOrderBys)) {
        // Create an OrderBy Expression based on the interval start time column name. We will need to
        // sort based on this as the first column.
        OrderByExpression defaultIntervalOrdering = OrderByExpression.newBuilder().setOrder(SortOrder.ASC).setExpression(QueryExpressionUtil.buildAttributeExpression(ColumnName.INTERVAL_START_TIME.name())).build();
        resolvedOrderBys.add(defaultIntervalOrdering);
    }
    resolvedOrderBys.addAll(existingOrderBys);
    return resolvedOrderBys;
}
Also used : ArrayList(java.util.ArrayList) OrderByExpression(org.hypertrace.gateway.service.v1.common.OrderByExpression)

Example 4 with Interval

use of org.hypertrace.gateway.service.v1.common.Interval in project gateway-service by hypertrace.

the class TimeAggregationsRequestHandlerTest method intervalStartTimeOrderingNotAddedIfAlreadyRequested.

@Test
public void intervalStartTimeOrderingNotAddedIfAlreadyRequested() {
    ExploreRequest exploreRequest = ExploreRequest.newBuilder().addTimeAggregation(TimeAggregation.newBuilder().setPeriod(Period.newBuilder().setUnit("SECONDS").setValue(60)).setAggregation(Expression.newBuilder().setFunction(FunctionExpression.newBuilder().setFunction(FunctionType.MAX).setAlias("MAX_Duration").addArguments(QueryExpressionUtil.buildAttributeExpression("duration"))))).addOrderBy(OrderByExpression.newBuilder().setOrder(SortOrder.DESC).setExpression(QueryExpressionUtil.buildAttributeExpression(ColumnName.INTERVAL_START_TIME.name()))).build();
    TimeAggregationsRequestHandler requestHandler = new TimeAggregationsRequestHandler(mock(QueryServiceClient.class), 500, mock(AttributeMetadataProvider.class));
    List<OrderByExpression> orderByExpressions = requestHandler.getRequestOrderByExpressions(exploreRequest);
    // Should maintain the interval start time order as only order by
    Assertions.assertEquals(List.of(OrderByExpression.newBuilder().setOrder(SortOrder.DESC).setExpression(QueryExpressionUtil.buildAttributeExpression(ColumnName.INTERVAL_START_TIME.name())).build()), orderByExpressions);
}
Also used : ExploreRequest(org.hypertrace.gateway.service.v1.explore.ExploreRequest) OrderByExpression(org.hypertrace.gateway.service.v1.common.OrderByExpression) AttributeMetadataProvider(org.hypertrace.gateway.service.common.AttributeMetadataProvider) QueryServiceClient(org.hypertrace.core.query.service.client.QueryServiceClient) Test(org.junit.jupiter.api.Test)

Example 5 with Interval

use of org.hypertrace.gateway.service.v1.common.Interval in project leetcode-practice by snehasishroy.

the class EraseNonOverlappingIntervals method eraseOverlapIntervalsSimplified.

// Same approach as my original approach, but the logic is more simplified as we are sorting by end time
// pick the interval ending first and only choose next interval that starts after this ends (non-overlapping)
// since we are picking the interval that finishes early, first; we are bound to get the maximum no of non-overlapping intervals
public int eraseOverlapIntervalsSimplified(int[][] intervals) {
    int n = intervals.length;
    if (n == 0) {
        return 0;
    }
    Interval[] input = new Interval[intervals.length];
    for (int i = 0; i < n; i++) {
        input[i] = new Interval(intervals[i][0], intervals[i][1]);
    }
    // sort by end
    Arrays.sort(input, Comparator.comparingInt(o -> o.end));
    // Result will store all the non-overlapping intervals
    Interval[] result = new Interval[n];
    int index = 0;
    result[index++] = input[0];
    for (int i = 1; i < n; i++) {
        if (input[i].start >= result[index - 1].end) {
            result[index++] = input[i];
        }
    }
    // Total intervals - non-overlapping intervals will give overlapping intervals
    return n - index;
}
Also used : Arrays(java.util.Arrays) Interval(common.Interval) Comparator(java.util.Comparator) Interval(common.Interval)

Aggregations

Interval (common.Interval)3 OrderByExpression (org.hypertrace.gateway.service.v1.common.OrderByExpression)3 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 Comparator (java.util.Comparator)2 QueryServiceClient (org.hypertrace.core.query.service.client.QueryServiceClient)2 AttributeMetadataProvider (org.hypertrace.gateway.service.common.AttributeMetadataProvider)2 ExploreRequest (org.hypertrace.gateway.service.v1.explore.ExploreRequest)2 Test (org.junit.jupiter.api.Test)2 Map (java.util.Map)1 TreeMap (java.util.TreeMap)1