def get_valid_array_idx(idx, last_idx):  # type: (int, int) -> int
    """Return valid array index value within range [0, last_idx].

    Negative values are interpreted such that it represent number of elements before the array end.
    If `idx` is greater than `last_idx` then it is interpreted as `last_idx` value.

    :param idx: The value of index we would like to get.
    :param last_idx: The maximum available index value.
    :return: Valid index value.
    """
    if idx >= 0:
        return min(idx, last_idx)
    else:
        return max(0, last_idx + idx)