-1

While solving Today's leetcode Daily challenge I wrote this code: (not the actual solution)

class Solution {
public:
    long long countSubarrays(vector<int>& nums, int minK, int maxK) {
        int  j = -1;
        int mintillnow = INT_MAX;
        int maxtillnow = INT_MIN;
        long long  count = 0;
        
            
        while(j<nums.size()){
            cout<<"why not running"<<endl;
            j++;
            mintillnow = min(nums[j],mintillnow);
            maxtillnow = max(nums[j],maxtillnow);
            if(mintillnow==minK && maxtillnow == maxK){
                count++;
            }
            if(mintillnow<minK || maxtillnow>maxK){
               mintillnow = INT_MAX;
               maxtillnow = INT_MIN;
            }
        }

        return count;
    }
};

The problem is when I initialize j = -1, the loop doesn't run and just returns count. But the loop works fine when I initialize j = 0 .

Why does this happen?

Darshan
  • 3
  • 2
  • 1
    Please don't use "competition" sites like that to learn the basics of programming or languages, that's not their purpose. And it simply doesn't work. Please invest in [some good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to learn C++ properly instead. – Some programmer dude Mar 04 '23 at 05:45
  • 1
    duplicates: [Why sizeof(int) is not greater than -1?](https://stackoverflow.com/q/24466857/995714), [why is `0 < v.size()-1` when the vector v is empty?](https://stackoverflow.com/q/51914679/995714) – phuclv Mar 04 '23 at 06:07
  • Why do you have compiler warnings disabled? Your compiler would tell you what is problematic with this code, if you allowed it to. – Drew Dormann Mar 04 '23 at 14:04

2 Answers2

0

The problem is that nums.size() returns a value that is unsigned. That means j will also be converted to an unsigned integer type. And -1 as unsigned is very large.

So the condition is simply never true.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Since j and nums.size() are of different type, they are subject to implicit conversion so that they become of the same type. Since they are both integer, the most precise one is chosen: in this case you most likely have int and size_t, and the language considers size_t the most precise of the two.

Hence -1 is converted to size_t and will end up being the max possible value for size_t (thus your while guard is always false)

pqnet
  • 6,070
  • 1
  • 30
  • 51