You are given $$$n$$$ segments on a number line, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th segments covers all integer points from $$$l_i$$$ to $$$r_i$$$ and has a value $$$w_i$$$.You are asked to select a subset of these segments (possibly, all of them). Once the subset is selected, it's possible to travel between two integer points if there exists a selected segment that covers both of them. A subset is good if it's possible to reach point $$$m$$$ starting from point $$$1$$$ in arbitrary number of moves.The cost of the subset is the difference between the maximum and the minimum values of segments in it. Find the minimum cost of a good subset.In every test there exists at least one good subset.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$; $$$2 \le m \le 10^6$$$) — the number of segments and the number of integer points. Each of the next $$$n$$$ lines contains three integers $$$l_i$$$, $$$r_i$$$ and $$$w_i$$$ ($$$1 \le l_i < r_i \le m$$$; $$$1 \le w_i \le 10^6$$$) — the description of the $$$i$$$-th segment. In every test there exists at least one good subset.

Print a single integer — the minimum cost of a good subset.

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    // var t = parseInt(lines[0]);
    var l = 0;
    var [n, m] = lines[l++].trim().split(' ').map(Number)
    var arr = lines.slice(l, l + n).map(str => str.trim().split(' ').map(Number))
    l += n
    console.log(solve(n, m, arr))
    // for (var i = 0; i < t; i++) {
    // var n = +lines[l++]
    // var a = lines[l++].trim().split(' ').map(Number)
    // var b = lines[l++].trim().split(' ').map(Number)
    // }
});

function solve(n, m, arr) {
    arr.sort((a, b) => a[2] - b[2])
// console.log(arr)
    const tree = []
    createTree(tree, 0, f(1), f(m, 1), 0)

    let i = 0
    let j = 0
    let ans = Infinity
    while (i < n) {
        let covered
        while (j < n && queryTree(tree, 0, f(1), f(m, 1)) === 0) {
            const [l, r, w] = arr[j]
            insertTree(tree, 0, f(l), f(r, 1), 1)
        // console.log(tree)

            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('j++', i, j, covered)
            // if (covered) {
                // console.log(ans, i, j, arr[j][2], arr[i][2])
                // break
            // }
            j++
        }
        // if (!covered) break
        if (queryTree(tree, 0, f(1), f(m, 1)) === 0) break
        // console.log('j++', i, j - 1, covered)
                ans = Math.min(ans, arr[j - 1][2] - arr[i][2])

        // while (i <= j) {
            const [l, r, w] = arr[i]
            insertTree(tree, 0, f(l), f(r, 1), -1)

            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('i++', i + 1, j - 1, covered)
            // if (!covered) break

            i++
        // ans = Math.min(ans, arr[j][2] - arr[i][2])
        // }
        // if (covered) break
    }
    return ans
}
function f(x, right) {
    return right ? x - 1 : x
}

function createTree(tree, p, left, right, val) {
    tree[p] = { left, right, val, lazy: val }
    if (left === right) return

    const mid = Math.floor((left + right) / 2)
    createTree(tree, 2 * p + 1, left, mid, val)
    createTree(tree, 2 * p + 2, mid + 1, right, val)
}
function initTree(tree, merge, arr) {
    for (let i = tree.length - 1; i >= 0; i--) {
        if (!tree[i]) continue
        const { left, right } = tree[i]
        tree[i].val = left === right
            ? arr[left % arr.length]
            : merge(tree[2 * i + 1].val, tree[2 * i + 2].val)
    }
}
function insertTree(tree, idx, l, r, val) {
    const { left, right, lazy } = tree[idx]
    if (l <= left && r >= right) {
        tree[idx].val += val
        tree[idx].lazy += val
        return
    }

    if (lazy && left !== right) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    const mid = Math.floor((left + right) / 2)
    if (l <= mid) {
        insertTree(tree, 2 * idx + 1, l, r, val)
    }
    if (r > mid) {
        insertTree(tree, 2 * idx + 2, l, r, val)
    }
    const merge = Math.min
    tree[idx].val = merge(tree[2 * idx + 1].val, tree[2 * idx + 2].val)
}
function queryTree(tree, idx, l, r) {
    const { left, right, val, lazy } = tree[idx]
    if (l <= left && r >= right) return val

    const mid = Math.floor((left + right) / 2)
    if (lazy) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    let a = Infinity
    let b = Infinity
    if (l <= mid) {
        a = queryTree(tree, 2 * idx + 1, l, r)
    }
    if (r > mid) {
        b = queryTree(tree, 2 * idx + 2, l, r)
    }
    const merge = Math.min
    return merge(a, b)
}

function _defineProperties(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}function _createClass(t,e,r){return e&&_defineProperties(t.prototype,e),r&&_defineProperties(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function _unsupportedIterableToArray(t,e){if(t){if("string"==typeof t)return _arrayLikeToArray(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray(t,e):void 0}}function _arrayLikeToArray(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function _createForOfIteratorHelperLoose(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=_unsupportedIterableToArray(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0;return function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var fs=require("fs"),configPath="./compe.config.json";function proc(t,e){if(global.MOD_=998244353,global.MOD_CUT=444595123,fs.existsSync(configPath)){if(!fs.existsSync(e))return void console.log("Input directory does not exist");var r=fs.readFileSync(e,{encoding:"utf-8"}),n=0;r=r.split(/ |\n|\r/g);for(var i,o=[],s=_createForOfIteratorHelperLoose(r);!(i=s()).done;){var a=i.value;a.length>0&&o.push(a)}global.rnum=function(t){return t?o.slice(n,n+=t).map((function(t){return+t})):+o[n++]},global.rstr=function(t){return t?o.slice(n,n+=t):o[n++]},global.rbig=function(t){return t?o.slice(n,n+=t).map((function(t){return BigInt(t)})):BigInt(o[n++])},global.print=function(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];for(var n=0,i=e;n<i.length;n++){var o=i[n];process.stdout.write(String(o))}},t()}else{var u="";process.stdin.on("data",(function(t){u+=t})),process.stdin.on("end",(function(){var e=0;u=u.split(/ |\n|\r/g);for(var r,n=[],i=_createForOfIteratorHelperLoose(u);!(r=i()).done;){var o=r.value;o.length>0&&n.push(o)}global.rnum=function(t){return t?n.slice(e,e+=t).map((function(t){return+t})):+n[e++]},global.rstr=function(t){return t?n.slice(e,e+=t):n[e++]},global.rbig=function(t){return t?n.slice(e,e+=t).map((function(t){return BigInt(t)})):BigInt(n[e++])};var s="";global.print=function(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];for(var n=0,i=e;n<i.length;n++){var o=i[n];s+=String(o)}},t(),console.log(s)}))}}function _defineProperties$1(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}function _createClass$1(t,e,r){return e&&_defineProperties$1(t.prototype,e),r&&_defineProperties$1(t,r),Object.defineProperty(t,"prototype",{writable:!1}),t}function _inheritsLoose(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,_setPrototypeOf(t,e)}function _getPrototypeOf(t){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},_getPrototypeOf(t)}function _setPrototypeOf(t,e){return _setPrototypeOf=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t},_setPrototypeOf(t,e)}function _isNativeReflectConstruct(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function _construct(t,e,r){return _construct=_isNativeReflectConstruct()?Reflect.construct:function(t,e,r){var n=[null];n.push.apply(n,e);var i=new(Function.bind.apply(t,n));return r&&_setPrototypeOf(i,r.prototype),i},_construct.apply(null,arguments)}function _isNativeFunction(t){return-1!==Function.toString.call(t).indexOf("[native code]")}function _wrapNativeSuper(t){var e="function"==typeof Map?new Map:void 0;return _wrapNativeSuper=function(t){if(null===t||!_isNativeFunction(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return _construct(t,arguments,_getPrototypeOf(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),_setPrototypeOf(r,t)},_wrapNativeSuper(t)}function _assertThisInitialized(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function _unsupportedIterableToArray$1(t,e){if(t){if("string"==typeof t)return _arrayLikeToArray$1(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray$1(t,e):void 0}}function _arrayLikeToArray$1(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function _createForOfIteratorHelperLoose$1(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=_unsupportedIterableToArray$1(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0;return function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}Object.defineProperty(exports,"__esModule",{value:!0});var ErrorGenerator,ForOfAdaptor=function(t){function e(t,e){this.it_=t,this.last_=e}var r=e.prototype;return r.next=function(){if(this.it_.equals(this.last_))return{done:!0,value:void 0};var t=this.it_;return this.it_=this.it_.next(),{done:!1,value:t.value}},r[t]=function(){return this},e}(Symbol.iterator),Container=function(t){function e(){}var r=e.prototype;return r.empty=function(){return 0===this.size()},r.rbegin=function(){return this.end().reverse()},r.rend=function(){return this.begin().reverse()},r[t]=function(){return new ForOfAdaptor(this.begin(),this.end())},r.toJSON=function(){for(var t,e=[],r=_createForOfIteratorHelperLoose$1(this);!(t=r()).done;){var n=t.value;e.push(n)}return e},e}(Symbol.iterator),NativeArrayIterator=function(){function t(t,e){this.data_=t,this.index_=e}var e=t.prototype;return e.index=function(){return this.index_},e.prev=function(){return--this.index_,this},e.next=function(){return++this.index_,this},e.advance=function(t){return this.index_+=t,this},e.equals=function(t){return this.data_===t.data_&&this.index_===t.index_},e.swap=function(t){var e=[t.data_,this.data_];this.data_=e[0],t.data_=e[1];var r=[t.index_,this.index_];this.index_=r[0],t.index_=r[1]},_createClass$1(t,[{key:"value",get:function(){return this.data_[this.index_]}}]),t}(),SetContainer=function(t){function e(e){var r;return(r=t.call(this)||this).data_=e(_assertThisInitialized(r)),r}_inheritsLoose(e,t);var r=e.prototype;return r.assign=function(t,e){this.clear(),this.insert(t,e)},r.clear=function(){this.data_.clear()},r.begin=function(){return this.data_.begin()},r.end=function(){return this.data_.end()},r.has=function(t){return!this.find(t).equals(this.end())},r.size=function(){return this.data_.size()},r.push=function(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];if(0===e.length)return this.size();var n=new NativeArrayIterator(e,0),i=new NativeArrayIterator(e,e.length);return this._Insert_by_range(n,i),this.size()},r.insert=function(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return 1===e.length?this._Insert_by_key(e[0]):e[0].next instanceof Function&&e[1].next instanceof Function?this._Insert_by_range(e[0],e[1]):this._Insert_by_hint(e[0],e[1])},r.erase=function(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return 1!==e.length||e[0]instanceof this.end().constructor&&e[0].source()===this?1===e.length?this._Erase_by_range(e[0]):this._Erase_by_range(e[0],e[1]):this._Erase_by_val(e[0])},r._Erase_by_range=function(t,e){void 0===e&&(e=t.next());var r=this.data_.erase(t,e);return this._Handle_erase(t,e),r},e}(Container),Exception=function(t){function e(r){var n;n=t.call(this,r)||this;var i=(this instanceof e?this.constructor:void 0).prototype;return Object.setPrototypeOf?Object.setPrototypeOf(_assertThisInitialized(n),i):n.__proto__=i,n}_inheritsLoose(e,t);var r=e.prototype;return r.what=function(){return this.message},r.toJSON=function(){return{name:this.name,message:this.message,stack:this.stack}},_createClass$1(e,[{key:"name",get:function(){return this.constructor.name}}]),e}(_wrapNativeSuper(Error)),LogicError=function(t){function e(e){return t.call(this,e)||this}return _inheritsLoose(e,t),e}(Exception),InvalidArgument=function(t){function e(e){return t.call(this,e)||this}return _inheritsLoose(e,t),e}(LogicError),OutOfRange=function(t){function e(e){return t.call(this,e)||this}return _inheritsLoose(e,t),e}(LogicError);!function(t){function e(t){if("string"==typeof t)return t;var e=t.constructor.name;return t.constructor.__MODULE&&(e=t.constructor.__MODULE+"."+e),"std."+e}t.get_class_name=e,t.empty=function(t,r){return new OutOfRange("Error on "+e(t)+"."+r+"(): it's empty container.")},t.negative_index=function(t,r,n){return new OutOfRange("Error on "+e(t)+"."+r+"(): parametric index is negative -> (index = "+n+").")},t.excessive_index=function(t,r,n,i){return new OutOfRange("Error on "+e(t)+"."+r+"(): parametric index is equal or greater than size -> (index = "+n+", size: "+i+").")},t.not_my_iterator=function(t,r){return new InvalidArgument("Error on "+e(t)+"."+r+"(): parametric iterator is not this container's own.")},t.erased_iterator=function(t,r){return new InvalidArgument("Error on "+e(t)+"."+r+"(): parametric iterator, it already has been erased.")},t.negative_iterator=function(t,r,n){return new OutOfRange("Error on "+e(t)+"."+r+"(): parametric iterator is directing negative position -> (index = "+n+").")},t.iterator_end_value=function(t,r){void 0===r&&(r="end");var n=e(t);return new OutOfRange("Error on "+n+".Iterator.value: cannot access to the "+n+"."+r+"().value.")},t.key_nout_found=function(t,r,n){throw new OutOfRange("Error on "+e(t)+"."+r+"(): unable to find the matched key -> "+n)}}(ErrorGenerator||(ErrorGenerator={}));var IAssociativeContainer,UniqueSet=function(t){function e(){return t.apply(this,arguments)||this}_inheritsLoose(e,t);var r=e.prototype;return r.count=function(t){return this.find(t).equals(this.end())?0:1},r.insert=function(){for(var e,r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];return(e=t.prototype.insert).call.apply(e,[this].concat(n))},r._Insert_by_range=function(t,e){for(;!t.equals(e);t=t.next())this._Insert_by_key(t.value)},r.extract=function(t){return t instanceof this.end().constructor?this._Extract_by_iterator(t):this._Extract_by_val(t)},r._Extract_by_val=function(t){var e=this.find(t);if(!0===e.equals(this.end()))throw ErrorGenerator.key_nout_found(this,"extract",t);return this._Erase_by_range(e),t},r._Extract_by_iterator=function(t){return!0===t.equals(this.end())||!1===this.has(t.value)?this.end():(this._Erase_by_range(t),t)},r._Erase_by_val=function(t){var e=this.find(t);return!0===e.equals(this.end())?0:(this._Erase_by_range(e),1)},r.merge=function(t){for(var e=t.begin();!e.equals(t.end());)!1===this.has(e.value)?(this.insert(e.value),e=t.erase(e)):e=e.next()},e}(SetContainer);!function(t){t.construct=function(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),n=1;n<e;n++)r[n-1]=arguments[n];var i,o;return r.length>=1&&r[0]instanceof Array?(i=function(){var e=r[0];t.push.apply(t,e)},o=r.slice(1)):r.length>=2&&r[0].next instanceof Function&&r[1].next instanceof Function?(i=function(){var e=r[0],n=r[1];t.assign(e,n)},o=r.slice(2)):(i=null,o=r),{ramda:i,tail:o}}}(IAssociativeContainer||(IAssociativeContainer={}));var is_node_=null;function is_node(){return null===is_node_&&(is_node_="object"==typeof global&&"object"==typeof global.process&&"object"==typeof global.process.versions&&void 0!==global.process.versions.node),is_node_}function _Get_root(){return null===__s_pRoot&&void 0===(__s_pRoot=is_node()?global:self).__s_iUID&&(__s_pRoot.__s_iUID=0),__s_pRoot}var ITreeContainer,__s_pRoot=null;function get_uid(t){if(t instanceof Object){if(!1===t.hasOwnProperty("__get_m_iUID")){var e=++_Get_root().__s_iUID;Object.defineProperty(t,"__get_m_iUID",{value:function(){return e}})}return t.__get_m_iUID()}return void 0===t?-1:0}function equal_to(t,e){return t=t?t.valueOf():t,e=e?e.valueOf():e,t instanceof Object&&t.equals instanceof Function?t.equals(e):t===e}function less(t,e){return t=t.valueOf(),e=e.valueOf(),t instanceof Object?t.less instanceof Function?t.less(e):get_uid(t)<get_uid(e):t<e}function hash(){for(var t=INIT_VALUE,e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];for(var i=0,o=r;i<o.length;i++){var s=o[i],a=typeof(s=s?s.valueOf():s);if("boolean"===a)t=_Hash_boolean(s,t);else if("number"===a||"bigint"===a)t=_Hash_number(s,t);else if("string"===a)t=_Hash_string(s,t);else if(s instanceof Object&&s.hashCode instanceof Function){var u=s.hashCode();if(1===r.length)return u;t^=u,t*=MULTIPLIER}else t=_Hash_number(get_uid(s),t)}return Math.abs(t)}function _Hash_boolean(t,e){return e^=t?1:0,e*=MULTIPLIER}function _Hash_number(t,e){return _Hash_string(t.toString(),e)}function _Hash_string(t,e){for(var r=0;r<t.length;++r)e^=t.charCodeAt(r),e*=MULTIPLIER;return Math.abs(e)}!function(t){t.construct=function(t,e,r){for(var n=null,i=less,o=arguments.length,s=new Array(o>3?o-3:0),a=3;a<o;a++)s[a-3]=arguments[a];if(1===s.length&&s[0]instanceof e){var u=s[0];i=u.key_comp(),n=function(){var e=u.begin(),r=u.end();t.assign(e,r)}}else{var h=IAssociativeContainer.construct.apply(IAssociativeContainer,[t].concat(s));n=h.ramda,h.tail.length>=1&&(i=h.tail[0])}r(i),null!==n&&n()},t.emplacable=function(t,e,r){var n=e.prev(),i=n.equals(t.end())||t.value_comp()(n.value,r);return i=i&&(e.equals(t.end())||t.value_comp()(r,e.value))}}(ITreeContainer||(ITreeContainer={}));var INIT_VALUE=2166136261,MULTIPLIER=16777619,Pair=function(){function t(t,e){this.first=t,this.second=e}var e=t.prototype;return e.equals=function(t){return equal_to(this.first,t.first)&&equal_to(this.second,t.second)},e.less=function(t){return!1===equal_to(this.first,t.first)?less(this.first,t.first):less(this.second,t.second)},e.hashCode=function(){return hash(this.first,this.second)},t}(),UniqueTreeSet=function(t){function e(){return t.apply(this,arguments)||this}_inheritsLoose(e,t);var r=e.prototype;return r.find=function(t){var e=this.lower_bound(t);return!e.equals(this.end())&&this._Key_eq(t,e.value)?e:this.end()},r.equal_range=function(t){var e=this.lower_bound(t);return new Pair(e,!e.equals(this.end())&&this._Key_eq(t,e.value)?e.next():e)},r.value_comp=function(){return this.key_comp()},r._Key_eq=function(t,e){return!this.key_comp()(t,e)&&!this.key_comp()(e,t)},r._Insert_by_key=function(t){var e=this.lower_bound(t);return!e.equals(this.end())&&this._Key_eq(e.value,t)?new Pair(e,!1):(e=this.data_.insert(e,t),this._Handle_insert(e,e.next()),new Pair(e,!0))},r._Insert_by_hint=function(t,e){if(ITreeContainer.emplacable(this,t,e)){var r=this.data_.insert(t,e);return this._Handle_insert(r,r.next()),r}return this._Insert_by_key(e).first},e}(UniqueSet),ListIterator=function(){function t(t,e,r){this.prev_=t,this.next_=e,this.value_=r}t._Set_prev=function(t,e){t.prev_=e},t._Set_next=function(t,e){t.next_=e};var e=t.prototype;return e.prev=function(){return this.prev_},e.next=function(){return this.next_},e._Try_value=function(){if(void 0===this.value_&&!0===this.equals(this.source().end()))throw ErrorGenerator.iterator_end_value(this.source())},e.equals=function(t){return this===t},_createClass$1(t,[{key:"value",get:function(){return this._Try_value(),this.value_}}]),t}(),Repeater=function(){function t(t,e){this.index_=t,this.value_=e}var e=t.prototype;return e.index=function(){return this.index_},e.next=function(){return++this.index_,this},e.equals=function(t){return this.index_===t.index_},_createClass$1(t,[{key:"value",get:function(){return this.value_}}]),t}();function advance(t,e){if(0===e)return t;if(t.advance instanceof Function)return t.advance(e);var r;if(e<0){if(!(t.prev instanceof Function))throw new InvalidArgument("Error on std.advance(): parametric iterator is not a bi-directional iterator, thus advancing to negative direction is not possible.");r=function(t){return t.prev()},e=-e}else r=function(t){return t.next()};for(;e-- >0;)t=r(t);return t}var ListContainer=function(t){function e(){var e;return(e=t.call(this)||this).end_=e._Create_iterator(null,null),e.clear(),e}_inheritsLoose(e,t);var r=e.prototype;return r.assign=function(t,e){this.clear(),this.insert(this.end(),t,e)},r.clear=function(){ListIterator._Set_prev(this.end_,this.end_),ListIterator._Set_next(this.end_,this.end_),this.begin_=this.end_,this.size_=0},r.resize=function(t){var e=t-this.size();e>0?this.insert(this.end(),e,void 0):e<0&&this.erase(advance(this.end(),-e),this.end())},r.begin=function(){return this.begin_},r.end=function(){return this.end_},r.size=function(){return this.size_},r.push_front=function(t){this.insert(this.begin_,t)},r.push_back=function(t){this.insert(this.end_,t)},r.pop_front=function(){if(!0===this.empty())throw ErrorGenerator.empty(this.end_.source().constructor.name,"pop_front");this.erase(this.begin_)},r.pop_back=function(){if(!0===this.empty())throw ErrorGenerator.empty(this.end_.source().constructor.name,"pop_back");this.erase(this.end_.prev())},r.push=function(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];if(0===e.length)return this.size();var n=new NativeArrayIterator(e,0),i=new NativeArrayIterator(e,e.length);return this._Insert_by_range(this.end(),n,i),this.size()},r.insert=function(t){if(t.source()!==this.end_.source())throw ErrorGenerator.not_my_iterator(this.end_.source(),"insert");if(!0===t.erased_)throw ErrorGenerator.erased_iterator(this.end_.source(),"insert");return 1==(arguments.length<=1?0:arguments.length-1)?this._Insert_by_repeating_val(t,1,arguments.length<=1?void 0:arguments[1]):2==(arguments.length<=1?0:arguments.length-1)&&"number"==typeof(arguments.length<=1?void 0:arguments[1])?this._Insert_by_repeating_val(t,arguments.length<=1?void 0:arguments[1],arguments.length<=2?void 0:arguments[2]):this._Insert_by_range(t,arguments.length<=1?void 0:arguments[1],arguments.length<=2?void 0:arguments[2])},r._Insert_by_repeating_val=function(t,e,r){var n=new Repeater(0,r),i=new Repeater(e);return this._Insert_by_range(t,n,i)},r._Insert_by_range=function(t,e,r){for(var n=t.prev(),i=null,o=0,s=e;!1===s.equals(r);s=s.next()){var a=this._Create_iterator(n,null,s.value);0===o&&(i=a),ListIterator._Set_next(n,a),n=a,++o}return!0===t.equals(this.begin())&&(this.begin_=i),ListIterator._Set_next(n,t),ListIterator._Set_prev(t,n),this.size_+=o,i},r.erase=function(t,e){return void 0===e&&(e=t.next()),this._Erase_by_range(t,e)},r._Erase_by_range=function(t,e){if(t.source()!==this.end_.source())throw ErrorGenerator.not_my_iterator(this.end_.source(),"insert");if(!0===t.erased_)throw ErrorGenerator.erased_iterator(this.end_.source(),"insert");if(t.equals(this.end_))return this.end_;var r=t.prev();ListIterator._Set_next(r,e),ListIterator._Set_prev(e,r);for(var n=t;!n.equals(e);n=n.next())n.erased_=!0,--this.size_;return t.equals(this.begin_)&&(this.begin_=e),e},r.swap=function(t){var e=[t.begin_,this.begin_];this.begin_=e[0],t.begin_=e[1];var r=[t.end_,this.end_];this.end_=r[0],t.end_=r[1];var n=[t.size_,this.size_];this.size_=n[0],t.size_=n[1]},e}(Container),ReverseIterator=function(){function t(t){this.base_=t.prev()}var e=t.prototype;return e.source=function(){return this.base_.source()},e.base=function(){return this.base_.next()},e.prev=function(){return this._Create_neighbor(this.base().next())},e.next=function(){return this._Create_neighbor(this.base_)},e.equals=function(t){return this.base_.equals(t.base_)},_createClass$1(t,[{key:"value",get:function(){return this.base_.value}}]),t}(),SetElementList=function(t){function e(e){var r;return(r=t.call(this)||this).associative_=e,r}_inheritsLoose(e,t);var r=e.prototype;return r._Create_iterator=function(t,r,n){return e.Iterator.create(this,t,r,n)},e._Swap_associative=function(t,e){var r=[e.associative_,t.associative_];t.associative_=r[0],e.associative_=r[1]},r.associative=function(){return this.associative_},e}(ListContainer);!function(t){var e=function(t){function e(e,r,n,i){var o;return(o=t.call(this,r,n,i)||this).source_=e,o}_inheritsLoose(e,t),e.create=function(t,r,n,i){return new e(t,r,n,i)};var n=e.prototype;return n.reverse=function(){return new r(this)},n.source=function(){return this.source_.associative()},e}(ListIterator);t.Iterator=e;var r=function(t){function e(){return t.apply(this,arguments)||this}return _inheritsLoose(e,t),e.prototype._Create_neighbor=function(t){return new e(t)},e}(ReverseIterator);t.ReverseIterator=r}(SetElementList||(SetElementList={}));var XTreeNode=function(){function t(t,e){this.value=t,this.color=e,this.parent=null,this.left=null,this.right=null}return _createClass$1(t,[{key:"grand",get:function(){return this.parent.parent}},{key:"sibling",get:function(){return this===this.parent.left?this.parent.right:this.parent.left}},{key:"uncle",get:function(){return this.parent.sibling}}]),t}(),XTree=function(){function t(t){this.root_=null,this.comp_=t,this.equal_=function(e,r){return!t(e,r)&&!t(r,e)}}var e=t.prototype;return e.clear=function(){this.root_=null},e.root=function(){return this.root_},e.get=function(t){var e=this.nearest(t);return null!==e&&this.equal_(t,e.value)?e:null},e.nearest=function(t){if(null===this.root_)return null;for(var e=this.root_;;){var r=null;if(this.comp_(t,e.value))r=e.left;else{if(!this.comp_(e.value,t))return e;r=e.right}if(null===r)break;e=r}return e},e._Fetch_maximum=function(t){for(;null!==t.right;)t=t.right;return t},e.insert=function(t){var e=this.nearest(t),r=new XTreeNode(t,1);null===e?this.root_=r:(r.parent=e,this.comp_(r.value,e.value)?e.left=r:e.right=r),this._Insert_case1(r)},e._Insert_case1=function(t){null===t.parent?t.color=0:this._Insert_case2(t)},e._Insert_case2=function(t){0!==this._Fetch_color(t.parent)&&this._Insert_case3(t)},e._Insert_case3=function(t){1===this._Fetch_color(t.uncle)?(t.parent.color=0,t.uncle.color=0,t.grand.color=1,this._Insert_case1(t.grand)):this._Insert_case4(t)},e._Insert_case4=function(t){t===t.parent.right&&t.parent===t.grand.left?(this._Rotate_left(t.parent),t=t.left):t===t.parent.left&&t.parent===t.grand.right&&(this._Rotate_right(t.parent),t=t.right),this._Insert_case5(t)},e._Insert_case5=function(t){t.parent.color=0,t.grand.color=1,t===t.parent.left&&t.parent===t.grand.left?this._Rotate_right(t.grand):this._Rotate_left(t.grand)},e.erase=function(t){var e=this.get(t);if(null!==e){if(null!==e.left&&null!==e.right){var r=this._Fetch_maximum(e.left);e.value=r.value,e=r}var n=null===e.right?e.left:e.right;0===this._Fetch_color(e)&&(e.color=this._Fetch_color(n),this._Erase_case1(e)),this._Replace_node(e,n),1===this._Fetch_color(this.root_)&&(this.root_.color=0)}},e._Erase_case1=function(t){null!==t.parent&&this._Erase_case2(t)},e._Erase_case2=function(t){1===this._Fetch_color(t.sibling)&&(t.parent.color=1,t.sibling.color=0,t===t.parent.left?this._Rotate_left(t.parent):this._Rotate_right(t.parent)),this._Erase_case3(t)},e._Erase_case3=function(t){0===this._Fetch_color(t.parent)&&0===this._Fetch_color(t.sibling)&&0===this._Fetch_color(t.sibling.left)&&0===this._Fetch_color(t.sibling.right)?(t.sibling.color=1,this._Erase_case1(t.parent)):this._Erase_case4(t)},e._Erase_case4=function(t){1===this._Fetch_color(t.parent)&&null!==t.sibling&&0===this._Fetch_color(t.sibling)&&0===this._Fetch_color(t.sibling.left)&&0===this._Fetch_color(t.sibling.right)?(t.sibling.color=1,t.parent.color=0):this._Erase_case5(t)},e._Erase_case5=function(t){t===t.parent.left&&null!==t.sibling&&0===this._Fetch_color(t.sibling)&&1===this._Fetch_color(t.sibling.left)&&0===this._Fetch_color(t.sibling.right)?(t.sibling.color=1,t.sibling.left.color=0,this._Rotate_right(t.sibling)):t===t.parent.right&&null!==t.sibling&&0===this._Fetch_color(t.sibling)&&0===this._Fetch_color(t.sibling.left)&&1===this._Fetch_color(t.sibling.right)&&(t.sibling.color=1,t.sibling.right.color=0,this._Rotate_left(t.sibling)),this._Erase_case6(t)},e._Erase_case6=function(t){t.sibling.color=this._Fetch_color(t.parent),t.parent.color=0,t===t.parent.left?(t.sibling.right.color=0,this._Rotate_left(t.parent)):(t.sibling.left.color=0,this._Rotate_right(t.parent))},e._Rotate_left=function(t){var e=t.right;this._Replace_node(t,e),t.right=e.left,null!==e.left&&(e.left.parent=t),e.left=t,t.parent=e},e._Rotate_right=function(t){var e=t.left;this._Replace_node(t,e),t.left=e.right,null!==e.right&&(e.right.parent=t),e.right=t,t.parent=e},e._Replace_node=function(t,e){null===t.parent?this.root_=e:t===t.parent.left?t.parent.left=e:t.parent.right=e,null!==e&&(e.parent=t.parent)},e._Fetch_color=function(t){return null===t?0:t.color},t}(),SetTree=function(t){function e(e,r,n){var i;return(i=t.call(this,n)||this).source_=e,i.key_comp_=r,i.key_eq_=function(t,e){return!r(t,e)&&!r(e,t)},i}_inheritsLoose(e,t),e._Swap_source=function(t,e){var r=[e.source_,t.source_];t.source_=r[0],e.source_=r[1]};var r=e.prototype;return r.get_by_key=function(t){var e=this.nearest_by_key(t);return null!==e&&this.key_eq_(t,e.value.value)?e:null},r.lower_bound=function(t){var e=this.nearest_by_key(t);return null===e?this.source_.end():this.key_comp_(e.value.value,t)?e.value.next():e.value},r.equal_range=function(t){return new Pair(this.lower_bound(t),this.upper_bound(t))},r.source=function(){return this.source_},r.key_comp=function(){return this.key_comp_},r.key_eq=function(){return this.key_eq_},r.value_comp=function(){return this.key_comp_},e}(XTree),UniqueSetTree=function(t){function e(e,r){return t.call(this,e,r,(function(t,e){return r(t.value,e.value)}))||this}_inheritsLoose(e,t);var r=e.prototype;return r.nearest_by_key=function(t){if(null===this.root_)return null;for(var e=this.root_;;){var r=e.value,n=null;if(this.key_comp()(t,r.value))n=e.left;else{if(!this.key_comp()(r.value,t))return e;n=e.right}if(null===n)break;e=n}return e},r.upper_bound=function(t){var e=this.nearest_by_key(t);if(null===e)return this.source().end();var r=e.value;return this.key_comp()(t,r.value)?r:r.next()},e}(SetTree);const TreeSet=function(t){function e(){var r;r=t.call(this,(function(t){return new SetElementList(t)}))||this;for(var n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return ITreeContainer.construct.apply(ITreeContainer,[_assertThisInitialized(r),e,function(t){r.tree_=new UniqueSetTree(_assertThisInitialized(r),t)}].concat(i)),r}_inheritsLoose(e,t);var r=e.prototype;return r.clear=function(){t.prototype.clear.call(this),this.tree_.clear()},r.swap=function(t){var e=[t.data_,this.data_];this.data_=e[0],t.data_=e[1],SetElementList._Swap_associative(this.data_,t.data_),UniqueSetTree._Swap_source(this.tree_,t.tree_);var r=[t.tree_,this.tree_];this.tree_=r[0],t.tree_=r[1]},r.key_comp=function(){return this.tree_.key_comp()},r.lower_bound=function(t){return this.tree_.lower_bound(t)},r.upper_bound=function(t){return this.tree_.upper_bound(t)},r._Handle_insert=function(t,e){for(;!t.equals(e);t=t.next())this.tree_.insert(t)},r._Handle_erase=function(t,e){for(;!t.equals(e);t=t.next())this.tree_.erase(t)},e}(UniqueTreeSet);function createCommonjsModule(t,e){return t(e={exports:{}},e.exports),e.exports}!function(t){t.Iterator=SetElementList.Iterator,t.ReverseIterator=SetElementList.ReverseIterator}(TreeSet||(TreeSet={}));var runtime_1=createCommonjsModule((function(t){var e=function(t){var e,r=Object.prototype,n=r.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},o=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",a=i.toStringTag||"@@toStringTag";function u(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{u({},"")}catch(t){u=function(t,e,r){return t[e]=r}}function h(t,e,r,n){var i=e&&e.prototype instanceof d?e:d,o=Object.create(i.prototype),s=new A(n||[]);return o._invoke=function(t,e,r){var n=c;return function(i,o){if(n===_)throw new Error("Generator is already running");if(n===p){if("throw"===i)throw o;return S()}for(r.method=i,r.arg=o;;){var s=r.delegate;if(s){var a=O(s,r);if(a){if(a===v)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===c)throw n=p,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=_;var u=l(t,e,r);if("normal"===u.type){if(n=r.done?p:f,u.arg===v)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(n=p,r.method="throw",r.arg=u.arg)}}}(t,r,s),o}function l(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=h;var c="suspendedStart",f="suspendedYield",_="executing",p="completed",v={};function d(){}function g(){}function y(){}var m={};u(m,o,(function(){return this}));var b=Object.getPrototypeOf,w=b&&b(b(z([])));w&&w!==r&&n.call(w,o)&&(m=w);var x=y.prototype=d.prototype=Object.create(m);function I(t){["next","throw","return"].forEach((function(e){u(t,e,(function(t){return this._invoke(e,t)}))}))}function E(t,e){function r(i,o,s,a){var u=l(t[i],t,o);if("throw"!==u.type){var h=u.arg,c=h.value;return c&&"object"==typeof c&&n.call(c,"__await")?e.resolve(c.__await).then((function(t){r("next",t,s,a)}),(function(t){r("throw",t,s,a)})):e.resolve(c).then((function(t){h.value=t,s(h)}),(function(t){return r("throw",t,s,a)}))}a(u.arg)}var i;this._invoke=function(t,n){function o(){return new e((function(e,i){r(t,n,e,i)}))}return i=i?i.then(o,o):o()}}function O(t,r){var n=t.iterator[r.method];if(n===e){if(r.delegate=null,"throw"===r.method){if(t.iterator.return&&(r.method="return",r.arg=e,O(t,r),"throw"===r.method))return v;r.method="throw",r.arg=new TypeError("The iterator does not provide a 'throw' method")}return v}var i=l(n,t.iterator,r.arg);if("throw"===i.type)return r.method="throw",r.arg=i.arg,r.delegate=null,v;var o=i.arg;return o?o.done?(r[t.resultName]=o.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,v):o:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,v)}function L(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function k(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function A(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(L,this),this.reset(!0)}function z(t){if(t){var r=t[o];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,s=function r(){for(;++i<t.length;)if(n.call(t,i))return r.value=t[i],r.done=!1,r;return r.value=e,r.done=!0,r};return s.next=s}}return{next:S}}function S(){return{value:e,done:!0}}return g.prototype=y,u(x,"constructor",y),u(y,"constructor",g),g.displayName=u(y,a,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===g||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,y):(t.__proto__=y,u(t,a,"GeneratorFunction")),t.prototype=Object.create(x),t},t.awrap=function(t){return{__await:t}},I(E.prototype),u(E.prototype,s,(function(){return this})),t.AsyncIterator=E,t.async=function(e,r,n,i,o){void 0===o&&(o=Promise);var s=new E(h(e,r,n,i),o);return t.isGeneratorFunction(r)?s:s.next().then((function(t){return t.done?t.value:s.next()}))},I(x),u(x,a,"Generator"),u(x,o,(function(){return this})),u(x,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var e=[];for(var r in t)e.push(r);return e.reverse(),function r(){for(;e.length;){var n=e.pop();if(n in t)return r.value=n,r.done=!1,r}return r.done=!0,r}},t.values=z,A.prototype={constructor:A,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(k),!t)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=e)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var r=this;function i(n,i){return a.type="throw",a.arg=t,r.next=n,i&&(r.method="next",r.arg=e),!!i}for(var o=this.tryEntries.length-1;o>=0;--o){var s=this.tryEntries[o],a=s.completion;if("root"===s.tryLoc)return i("end");if(s.tryLoc<=this.prev){var u=n.call(s,"catchLoc"),h=n.call(s,"finallyLoc");if(u&&h){if(this.prev<s.catchLoc)return i(s.catchLoc,!0);if(this.prev<s.finallyLoc)return i(s.finallyLoc)}else if(u){if(this.prev<s.catchLoc)return i(s.catchLoc,!0)}else{if(!h)throw new Error("try statement without catch or finally");if(this.prev<s.finallyLoc)return i(s.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var o=i;break}}o&&("break"===t||"continue"===t)&&o.tryLoc<=e&&e<=o.finallyLoc&&(o=null);var s=o?o.completion:{};return s.type=t,s.arg=e,o?(this.method="next",this.next=o.finallyLoc,v):this.complete(s)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),v},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),k(r),v}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var i=n.arg;k(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:z(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),v}},t}(t.exports);try{regeneratorRuntime=e}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}})),Deque=function(t){function e(t){this.head=0,this.tail=0,this.mask=1,this.list=new Array(2),t&&this.extend(t)}var r=e.prototype;return r.extend=function(t){for(var e,r=_createForOfIteratorHelperLoose(t);!(e=r()).done;){var n=e.value;this.push(n)}return this},r.extendFront=function(t){for(var e,r=_createForOfIteratorHelperLoose(t);!(e=r()).done;){var n=e.value;this.pushFront(n)}return this},r._resize=function(t,e){var r=this.head,n=this.mask;if(this.head=0,this.tail=t,this.mask=e-1,0!==r){for(var i=new Array(e),o=0;o<t;o++)i[o]=this.list[r+o&n];this.list=i}else this.list.length=e},r.push=function(t){return this.list[this.tail]=t,this.tail=this.tail+1&this.mask,this.head===this.tail&&this._resize(this.list.length,this.list.length<<1),this},r.pushFront=function(t){return this.head=this.head-1&this.mask,this.list[this.head]=t,this.head===this.tail&&this._resize(this.list.length,this.list.length<<1),this},r.clear=function(){this.head=0,this.tail=0},r.at=function(t){var e=this.head,r=this.size,n=this.tail,i=this.list;if((0|t)!==t||t>=r||t<-r)throw new RangeError("deque index out of range");return i[(t>=0?e:n)+t&this.mask]},r.indexOf=function(t,e){void 0===e&&(e=0);for(var r=this.head,n=this.list,i=this.size,o=this.mask,s=e>=0?e:e<-i?0:i+e;s<i;s++)if(n[r+s&o]===t)return s;return-1},r.has=function(t){for(var e=this.head,r=this.list,n=this.size,i=this.mask,o=0;o<n;o++)if(r[e+o&i]===t)return!0;return!1},r.insert=function(t,e){var r=this.head+t&this.mask,n=this.tail;for(this.tail=this.tail+1&this.mask;n!==r;){var i=n-1&this.mask;this.list[n]=this.list[i],n=i}return this.list[r]=e,this.head===this.tail&&this._resize(this.list.length,this.list.length<<1),this},r.pop=function(){if(this.head===this.tail)throw new RangeError("pop from an empty deque");this.tail=this.tail-1&this.mask;var t=this.list[this.tail];return this.list[this.tail]=void 0,this.size<this.mask>>>1&&this._resize(this.size,this.list.length>>>1),t},r.popFront=function(){if(this.head===this.tail)throw new RangeError("pop from an empty deque");var t=this.list[this.head];return this.list[this.head]=void 0,this.head=this.head+1&this.mask,this.size<this.mask>>>1&&this._resize(this.size,this.list.length>>>1),t},r.delete=function(t){if(t>=this.size||t<0)throw new RangeError("deque index out of range");for(var e=this.head+t&this.mask;e!==this.tail;){var r=e+1&this.mask;this.list[e]=this.list[r],e=r}return this.tail=this.tail-1&this.mask,this.size<this.mask>>>1&&this._resize(this.size,this.list.length>>>1),this},r.reverse=function(){for(var t=this.head,e=this.tail,r=this.size,n=this.mask,i=0;i<~~(r/2);i++){var o=e-i-1&n,s=t+i&n,a=this.list[o];this.list[o]=this.list[s],this.list[s]=a}return this},r.rotate=function(t){void 0===t&&(t=1);var e=this.head,r=this.tail;if(0===t||e===r)return this;if(this.head=e-t&this.mask,this.tail=r-t&this.mask,t>0)for(var n=1;n<=t;n++){var i=e-n&this.mask,o=r-n&this.mask;this.list[i]=this.list[o],this.list[o]=void 0}else for(var s=0;s>t;s--){var a=r-s&this.mask,u=e-s&this.mask;this.list[a]=this.list[u],this.list[u]=void 0}return this},r.entries=runtime_1.mark((function t(){var e,r,n,i,o;return runtime_1.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:e=this.head,r=this.size,n=this.list,i=this.mask,o=0;case 2:if(!(o<r)){t.next=8;break}return t.next=5,n[e+o&i];case 5:o++,t.next=2;break;case 8:case"end":return t.stop()}}),t,this)})),r.keys=function(){return this.entries()},r.values=function(){return this.entries()},r[t]=function(){return this.entries()},_createClass(e,[{key:"front",get:function(){if(this.size)return this.list[this.head];throw new RangeError("deque index out of range")}},{key:"back",get:function(){if(this.size)return this.list[this.tail-1&this.mask];throw new RangeError("deque index out of range")}},{key:"size",get:function(){return this.tail-this.head&this.mask}}]),e}(Symbol.iterator),multiArray=function(t){if(0==(arguments.length<=1?0:arguments.length-1))throw new Error("Please insert dimension values");if((arguments.length<=1?0:arguments.length-1)>=1){var e;if("object"==typeof t)throw new Error("The value can not be object");var r=[t,[]],n=0,i=1;r[0]=new Array((e=(arguments.length<=1?0:arguments.length-1)-1+1)<1||arguments.length<=e?void 0:arguments[e]);for(var o=0;o<r[0].length;o++)r[0][o]=t;for(var s=(arguments.length<=1?0:arguments.length-1)-2;s>=0;s--){if(!Number.isInteger(s+1<1||arguments.length<=s+1?void 0:arguments[s+1]))throw new Error("Please pass integer arguments for array size");r[i]=new Array(s+1<1||arguments.length<=s+1?void 0:arguments[s+1]);for(var a=0;a<(s+1<1||arguments.length<=s+1?void 0:arguments[s+1]);a++)r[i][a]=r[n].slice();var u=[i,n];n=u[0],i=u[1]}return r[n]}},vectorArray=function(t){for(var e=new Array(t),r=0;r<t;r++)e[r]=[];return e},DSU=function(){function t(t){this.p=multiArray(-1,t+1)}var e=t.prototype;return e.group=function(t){return this.p[t]<0?t:(this.p[t]=this.group(this.p[t]),this.p[t])},e.join=function(t,e){if((t=this.group(t))==(e=this.group(e)))return!1;if(this.p[t]>this.p[e]){var r=[e,t];t=r[0],e=r[1]}return this.p[t]+=this.p[e],this.p[e]=t,!0},e.size=function(t){return t=this.group(t),-this.p[t]},t}(),PriorityQueue=function(){function t(t){this.comparator=t||function(t,e){return t<e},this.elem=[]}var e=t.prototype;return e.swap=function(t,e){var r=[this.elem[e],this.elem[t]];this.elem[t]=r[0],this.elem[e]=r[1]},e.push=function(t){for(var e=this.elem.push(t)-1,r=0;e>0&&(r=e>>1,!this.comparator(this.elem[e],this.elem[r]));)this.swap(e,r),e=r},e.pop=function(){var t=this.top,e=this.elem.pop(),r=this.size;if(0==r)return t;this.elem[0]=e;for(var n=0,i=0,o=0,s=0;n<r&&(i=n,s=2+(n<<1),(o=1+(n<<1))<r&&!this.comparator(this.elem[o],this.elem[i])&&(i=o),s<r&&!this.comparator(this.elem[s],this.elem[i])&&(i=s),i!=n);)this.swap(i,n),n=i;return t},_createClass(t,[{key:"size",get:function(){return this.elem.length}},{key:"top",get:function(){if(0==this.elem.length)throw new Error("PriorityQueue is empty");return this.elem[0]}}]),t}(),SparseTable=function(){function t(t,e){var r=this;void 0===e&&(e=function(t,e){return t<e?t:e}),this.maxGap=0;var n=t.length;this.logFactor=this.floorLog2(n),this.merger=e,this.cont=Array(n).fill(0).map((function(){return Array(r.logFactor+1)}));for(var i=0;i<n;i++)this.cont[i][0]=t[i];for(var o=1;o<=this.logFactor;o++)for(var s=0;s+(1<<o)-1<n;s++)this.cont[s][o]=e(this.cont[s][o-1],this.cont[s+(1<<o-1)][o-1])}var e=t.prototype;return e.floorLog2=function(t){return 31-Math.clz32(t)},e.query=function(t,e){return this.maxGap=this.floorLog2(e-t+1),this.merger(this.cont[t][this.maxGap],this.cont[e-(1<<this.maxGap)+1][this.maxGap])},t}(),FenwickTree=function(){function t(t,e,r){void 0===e&&(e=0),void 0===r&&(r=function(t,e){return t+e}),this.identityValue=e,this.updateMethod=r,this.elemCount=t,this.cont=Array(t+1).fill(e)}var e=t.prototype;return e.query=function(t){for(var e=this.identityValue;t>=0;t=(t&t+1)-1)e=this.updateMethod(e,this.cont[t]);return e},e.update=function(t,e){for(;t<=this.elemCount;t|=t+1)this.cont[t]=this.updateMethod(this.cont[t],e)},t}(),SegmentTree=function(){function t(t,e,r,n){if(void 0===n&&(n=null),this.identityValue=e,this.merger=r,this.elemCount=t,this.log=Math.ceil(Math.log2(t)),this.size=1<<this.log,this.cont=Array(t<<1).fill(this.identityValue),n){for(var i=0;i<t;i++)this.cont[this.size+i]=n[i];for(var o=this.size-1;o>=1;o--)this.internalUpdate(o)}}var e=t.prototype;return e.internalUpdate=function(t){this.cont[t]=this.merger(this.cont[t<<1],this.cont[t<<1|1])},e.set=function(t,e){t+=this.size,this.cont[t]=e;for(var r=1;r<=this.log;r++)this.internalUpdate(t>>r)},e.get=function(t){return t?this.cont[t+this.size]:this.cont.slice(this.size,this.size+this.elemCount)},e.query=function(t,e){void 0===t&&(t=0),void 0===e&&(e=this.elemCount-1),e++;var r=this.identityValue,n=this.identityValue;for(t+=this.size,e+=this.size;t<e;)1&t&&(r=this.merger(r,this.cont[t++])),1&e&&(n=this.merger(this.cont[--e],n)),t>>=1,e>>=1;return this.merger(r,n)},e.all=function(){return this.cont[1]},t}(),LazySegmentTree=function(){function t(t,e,r,n,i,o,s){if(void 0===s&&(s=null),this.identityValue=e,this.merger=r,this.identityLazy=n,this.pusher=i,this.modifier=o,this.log=Math.ceil(Math.log2(t)),this.size=1<<this.log,this.cont=Array(this.size<<1).fill(this.identityValue),this.lazyCont=Array(this.size).fill(n),s){for(var a=0;a<t;a++)this.cont[this.size+a]=s[a];for(var u=this.size-1;u>=1;u--)this.internalUpdate(u)}}var e=t.prototype;return e.internalUpdate=function(t){this.cont[t]=this.merger(this.cont[t<<1],this.cont[t<<1|1])},e.internalModify=function(t,e){e!==this.identityLazy&&(this.cont[t]=this.modifier(this.cont[t],e),t<this.size&&(this.lazyCont[t]=this.pusher(this.lazyCont[t],e)))},e.internalPush=function(t){this.lazyCont[t]!==this.identityLazy&&(this.internalModify(t<<1,this.lazyCont[t]),this.internalModify(t<<1|1,this.lazyCont[t]),this.lazyCont[t]=this.identityLazy)},e.set=function(t,e){t+=this.size;for(var r=this.log;r>=1;r--)this.internalPush(t>>r);this.cont[t]=e;for(var n=1;n<=this.log;n++)this.internalUpdate(t>>n)},e.get=function(t){t+=this.size;for(var e=this.log;e>=1;e--)this.internalPush(t>>e);return this.cont[t]},e.query=function(t,e){e++,t+=this.size,e+=this.size;for(var r=this.log;r>=1;r--)t>>r<<r!=t&&this.internalPush(t>>r),e>>r<<r!=e&&this.internalPush(e-1>>r);for(var n=this.identityValue,i=this.identityValue;t<e;)1&t&&(n=this.merger(n,this.cont[t++])),1&e&&(i=this.merger(this.cont[--e],i)),t>>=1,e>>=1;return this.merger(n,i)},e.all=function(){return this.cont[1]},e.update=function(t,e,r){e++,t+=this.size,e+=this.size;for(var n=this.log;n>=1;n--)t>>n<<n!=t&&this.internalPush(t>>n),e>>n<<n!=e&&this.internalPush(e-1>>n);for(var i=t,o=e;t<e;)1&t&&this.internalModify(t++,r),1&e&&this.internalModify(--e,r),t>>=1,e>>=1;t=i,e=o;for(var s=1;s<=this.log;s++)t>>s<<s!=t&&this.internalUpdate(t>>s),e>>s<<s!=e&&this.internalUpdate(e-1>>s)},t}(),defaultComparator=function(t,e){return t<e},lowerBound=function(t,e,r,n,i){var o;for(void 0===r&&(r=0),void 0===n&&(n=0),void 0===i&&(i=defaultComparator),n||(n=t.length);r<n;)i(t[o=r+(n-r>>>1)],e)?r=o+1:n=o;return r},upperBound=function(t,e,r,n,i){var o;for(void 0===r&&(r=0),void 0===n&&(n=0),void 0===i&&(i=defaultComparator),n||(n=t.length);r<n;)i(e,t[o=r+(n-r>>>1)])?n=o:r=o+1;return r},binarySearch=function(t,e,r){for(var n,i=null;t<=e;)r(n=t+e>>1)?(i=n,e=n-1):t=n+1;return i},ternarySearch=function(t,e,r,n,i){var o,s;if(void 0===n&&(n=!1),void 0===i&&(i=200),n)for(;i--;)s=e-(e-t)/3,r(o=t+(e-t)/3)<r(s)?t=o:e=s;else for(;i--;)o=t+(e-t)/3,r(s=e-(e-t)/3)<r(o)?t=o:e=s;return r(o)},integralExtremumSearch=function(t,e,r,n){if(void 0===n&&(n=!1),n){var i,o,s=r(t);for(t++;t<=e;)o=r(i=t+e>>1),r(i-1)<o?(s=o,t=i+1):e=i-1;return s}var a,u,h=r(t);for(t++;t<=e;)u=r(a=t+e>>1),r(a-1)>u?(h=u,t=a+1):e=a-1;return h},Graph=function(){function t(t){this.g=vectorArray(t+1),this.vis=multiArray(!1,t+1),this.par=multiArray(-1,t+1)}var e=t.prototype;return e.addEdge=function(t,e,r){this.g[t].push({to:e,prop:r})},e.addBiEdge=function(t,e,r){this.addEdge(t,e,r),this.addEdge(e,t,r)},e.reset=function(){this.vis=multiArray(!1,this.g.length),this.par=multiArray(-1,this.g.length)},t}(),dfs=function(t,e,r,n){var i=new Deque;for(i.push(e);i.size;){var o=i.back;if(t.vis[o])n(o,t),i.pop();else{t.vis[o]=!0,r(o,t);for(var s,a=_createForOfIteratorHelperLoose(t.g[o]);!(s=a()).done;){var u=s.value;t.vis[u.to]||(t.par[u.to]=o,i.push(u.to))}}}},bfs=function(t,e,r){var n=new Deque;if(n.push(e),Array.isArray(e))for(var i,o=_createForOfIteratorHelperLoose(e);!(i=o()).done;){var s=i.value;t.vis[s]=!0,n.push(s)}else t.vis[e]=!0,n.push(e);for(;n.size;){var a=n.pop();r(a,t);for(var u,h=_createForOfIteratorHelperLoose(t.g[a]);!(u=h()).done;){var l=u.value;t.vis[l.to]||(t.par[l.to]=a,n.push(l.to),t.vis[l.to]=!0)}}},mst=function(t){for(var e=0,r=[],n=[],i=0;i<t.g.length;i++)for(var o,s=_createForOfIteratorHelperLoose(t.g[i]);!(o=s()).done;){var a=o.value;i<a.to&&r.push({from:i,to:a.to,weight:a.prop.weight})}var u=new DSU(t.g.length);r.sort((function(t,e){return t.weight-e.weight}));for(var h=0,l=r;h<l.length;h++){var c=l[h];u.join(c.from,c.to)&&(e+=c.weight,n.push(c))}return{mst:e,mstEdges:n}},spfa=function(t,e){t.reset();var r,n=Number.MAX_SAFE_INTEGER,i=multiArray(n,t.g.length),o=multiArray(!1,t.g.length),s=new Deque;if(Array.isArray(e))for(var a,u=_createForOfIteratorHelperLoose(e);!(a=u()).done;){var h=a.value;s.push(h),o[h]=!0,i[h]=0}else s.push(e),o[e]=!0,i[e]=0;for(;s.size;){o[r=s.pop()]=!1;for(var l,c=_createForOfIteratorHelperLoose(t.g[r]);!(l=c()).done;){var f=l.value;i[f.to]>i[r]+f.prop.weight&&(i[f.to]=i[r]+f.prop.weight,t.par[f.to]=r,o[f.to]||(o[f.to]=!0,s.push(f.to)))}}return{parArray:t.par,distArray:i}},dijkstra=function(t,e){t.reset();var r=new PriorityQueue((function(t,e){return t.dist>e.dist})),n=Number.MAX_SAFE_INTEGER,i=multiArray(n,t.g.length);if(Array.isArray(e))for(var o,s=_createForOfIteratorHelperLoose(e);!(o=s()).done;){var a=o.value;r.push({node:a,dist:0}),i[a]=0}else r.push({node:e,dist:0}),i[e]=0;for(;r.size;){var u=r.pop();if(i[u.node]===u.dist)for(var h,l=_createForOfIteratorHelperLoose(t.g[u.node]);!(h=l()).done;){var c=h.value;i[c.to]>i[u.node]+c.prop.weight&&(i[c.to]=i[u.node]+c.prop.weight,t.par[c.to]=u.node,r.push({node:c.to,dist:i[c.to]}))}}return{parArray:t.par,distArray:i}},setMod=function(t){global.MOD_=t,global.MOD_CUT=1099511627776%t},add=function(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];for(var n=e.length-1;n>=1;n--)e[0]+=e[n],e[0]=e[0]>=global.MOD_?e[0]-global.MOD_:e[0];return e[0]},sub=function(t,e){return(t+=global.MOD_-e)>=global.MOD_?t-global.MOD_:t},mul=function(){for(var t=arguments.length<=0?void 0:arguments[0],e=1;e<arguments.length;e++)t=((t>>20)*((e<0||arguments.length<=e?void 0:arguments[e])>>20)*global.MOD_CUT+(4293918720&t)*(1048575&(e<0||arguments.length<=e?void 0:arguments[e]))+(1048575&t)*(e<0||arguments.length<=e?void 0:arguments[e]))%global.MOD_;return t},pow=function(t,e){for(var r=1;e;)1&e&&(r=mul(r,t)),t=mul(t,t),e>>>=1;return r},inv=function(t){return a<0?a+global.MOD_:a},factSetup=function(t){void 0===t&&(t=2e5),global.factorial=Array(t+1).fill(1),global.invFactorial=Array(t+1).fill(1);for(var e=1;e<=t;e++)global.factorial[e]=mul(global.factorial[e-1],e);global.invFactorial[t]=inv();for(var r=t-1;r>=1;r--)global.invFactorial[r]=mul(global.invFactorial[r+1],r+1)},binom=function(t,e){return e>t?0:mul(global.factorial[t],global.invFactorial[e],global.invFactorial[t-e])},fact=function(t){return global.factorial[t]};

function main() {
  // write your code from here
  let [n, m] = rnum(2);
  let segs = Array(n).fill(0);
  for (let i = 0; i < n; i ++) {
    let [l, r, w] = rnum(3);
    l --;
    r --;
    segs[i] = {l, r, w};
  }
  segs.sort((a, b) => a.w - b.w);
  const INF = 1 << 30;
  let tree = new LazySegmentTree(
    m - 1, INF, (a, b) => a < b ? a : b,
    INF, (a, b) => b, (a, b) => b, Array(m - 1).fill(-INF)
  );
  let ans = INF;
  for (let seg of segs) {
    tree.update(seg.l, seg.r - 1, seg.w);
    let best = seg.w - tree.all()
    ans = ans < best ? ans : best;
  }
  print(ans);
}
proc(main, 'input.txt');

// Generated with compe.js - https://github.com/polarity-cf/compe.js

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    // var t = parseInt(lines[0]);
    var l = 0;
    var [n, m] = lines[l++].trim().split(' ').map(Number)
    var arr = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))
    l += m
    try {
    console.log(solve(n, m, arr))
    } catch (e) {
        console.log(e)
    }
    // for (var i = 0; i < t; i++) {
    // var n = +lines[l++]
    // var a = lines[l++].trim().split(' ').map(Number)
    // var b = lines[l++].trim().split(' ').map(Number)
    // }
});

function solve(n, m, arr) {
    arr.sort((a, b) => a[2] - b[2])
// console.log(arr)
    const tree = []
    createTree(tree, 0, f(1), f(m, 1), 0)

    let i = 0
    let j = 0
    let ans = Infinity
    while (i < n) {
        let covered
        while (j < n && queryTree(tree, 0, f(1), f(m, 1)) === 0) {
    try{
            const [l, r, w] = arr[j]
    }catch(e) {
        throw arr.length
    }
            const [l, r, w] = arr[j]
            insertTree(tree, 0, f(l), f(r, 1), 1)
        // console.log(tree)

            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('j++', i, j, covered)
            // if (covered) {
                // console.log(ans, i, j, arr[j][2], arr[i][2])
                // break
            // }
            j++
        }

        // if (!covered) break
        if (queryTree(tree, 0, f(1), f(m, 1)) === 0) break
    try{
        // console.log('j++', i, j - 1, covered)
                ans = Math.min(ans, arr[j - 1][2] - arr[i][2])

        // while (i <= j) {
            const [l, r, w] = arr[i]
            insertTree(tree, 0, f(l), f(r, 1), -1)

    }catch(e) {
        throw -4
    }
            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('i++', i + 1, j - 1, covered)
            // if (!covered) break

            i++
        // ans = Math.min(ans, arr[j][2] - arr[i][2])
        // }
        // if (covered) break
    }
    return ans
}
function f(x, right) {
    return right ? x - 1 : x
}

function createTree(tree, p, left, right, val) {
    tree[p] = { left, right, val, lazy: val }
    if (left === right) return

    const mid = Math.floor((left + right) / 2)
    createTree(tree, 2 * p + 1, left, mid, val)
    createTree(tree, 2 * p + 2, mid + 1, right, val)
}
function initTree(tree, merge, arr) {
    for (let i = tree.length - 1; i >= 0; i--) {
        if (!tree[i]) continue
        const { left, right } = tree[i]
        tree[i].val = left === right
            ? arr[left % arr.length]
            : merge(tree[2 * i + 1].val, tree[2 * i + 2].val)
    }
}
function insertTree(tree, idx, l, r, val) {
        try {
            tree[idx].left
        } catch (e) {
            throw 7e8 + idx
        }
    const { left, right, lazy } = tree[idx]
        try {
    if (l <= left && r >= right) {
        tree[idx].val += val
        tree[idx].lazy += val
        return
    }
        } catch (e) {
            throw 9e8 + idx
        }

        try {
    if (lazy && left !== right) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }
        } catch (e) {
            throw 8e8 + idx
        }

    const mid = Math.floor((left + right) / 2)
    if (l <= mid) {
        try {
        insertTree(tree, 2 * idx + 1, l, r, val)
        } catch (e) {
            throw -1
        }
    }
    if (r > mid) {
        try {
            // throw 'sb'
        insertTree(tree, 2 * idx + 2, l, r, val)
        } catch (e) {
            throw -2
        }
    }
    const merge = Math.min
    tree[idx].val = merge(tree[2 * idx + 1].val, tree[2 * idx + 2].val)
}
function queryTree(tree, idx, l, r) {
    const { left, right, val, lazy } = tree[idx]
    if (l <= left && r >= right) return val

    const mid = Math.floor((left + right) / 2)
    if (lazy) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    let a = Infinity
    let b = Infinity
    if (l <= mid) {
        try {
        a = queryTree(tree, 2 * idx + 1, l, r)
        }catch(e) {
        throw -5
        }
    }
    if (r > mid) {
        try {
        b = queryTree(tree, 2 * idx + 2, l, r)
        }catch(e) {
        throw -6
        }
    }
    const merge = Math.min
    return merge(a, b)
}

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    // var t = parseInt(lines[0]);
    var l = 0;
    var [n, m] = lines[l++].trim().split(' ').map(Number)
    var arr = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))
    l += m
    try {
    console.log(solve(n, m, arr))
    } catch (e) {
        console.log(e)
    }
    // for (var i = 0; i < t; i++) {
    // var n = +lines[l++]
    // var a = lines[l++].trim().split(' ').map(Number)
    // var b = lines[l++].trim().split(' ').map(Number)
    // }
});

function solve(n, m, arr) {
    arr.sort((a, b) => a[2] - b[2])
// console.log(arr)
    const tree = []
    createTree(tree, 0, f(1), f(m, 1), 0)

    let i = 0
    let j = 0
    let ans = Infinity
    while (i < n) {
        let covered
        while (j < n && queryTree(tree, 0, f(1), f(m, 1)) === 0) {
    // try{
            const [l, r, w] = arr[j]
            insertTree(tree, 0, f(l), f(r, 1), 1)
    // }catch(e) {
    //     throw -7
    // }
        // console.log(tree)

            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('j++', i, j, covered)
            // if (covered) {
                // console.log(ans, i, j, arr[j][2], arr[i][2])
                // break
            // }
            j++
        }

        // if (!covered) break
        if (queryTree(tree, 0, f(1), f(m, 1)) === 0) break
    try{
        // console.log('j++', i, j - 1, covered)
                ans = Math.min(ans, arr[j - 1][2] - arr[i][2])

        // while (i <= j) {
            const [l, r, w] = arr[i]
            insertTree(tree, 0, f(l), f(r, 1), -1)

    }catch(e) {
        throw -4
    }
            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('i++', i + 1, j - 1, covered)
            // if (!covered) break

            i++
        // ans = Math.min(ans, arr[j][2] - arr[i][2])
        // }
        // if (covered) break
    }
    return ans
}
function f(x, right) {
    return right ? x - 1 : x
}

function createTree(tree, p, left, right, val) {
    tree[p] = { left, right, val, lazy: val }
    if (left === right) return

    const mid = Math.floor((left + right) / 2)
    createTree(tree, 2 * p + 1, left, mid, val)
    createTree(tree, 2 * p + 2, mid + 1, right, val)
}
function initTree(tree, merge, arr) {
    for (let i = tree.length - 1; i >= 0; i--) {
        if (!tree[i]) continue
        const { left, right } = tree[i]
        tree[i].val = left === right
            ? arr[left % arr.length]
            : merge(tree[2 * i + 1].val, tree[2 * i + 2].val)
    }
}
function insertTree(tree, idx, l, r, val) {
        try {
            tree[idx].left
        } catch (e) {
            throw 7e8 + idx
        }
    const { left, right, lazy } = tree[idx]
        try {
    if (l <= left && r >= right) {
        tree[idx].val += val
        tree[idx].lazy += val
        return
    }
        } catch (e) {
            throw 9e8 + idx
        }

        try {
    if (lazy && left !== right) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }
        } catch (e) {
            throw 8e8 + idx
        }

    const mid = Math.floor((left + right) / 2)
    if (l <= mid) {
        try {
        insertTree(tree, 2 * idx + 1, l, r, val)
        } catch (e) {
            throw -1
        }
    }
    if (r > mid) {
        try {
            // throw 'sb'
        insertTree(tree, 2 * idx + 2, l, r, val)
        } catch (e) {
            throw -2
        }
    }
    const merge = Math.min
    tree[idx].val = merge(tree[2 * idx + 1].val, tree[2 * idx + 2].val)
}
function queryTree(tree, idx, l, r) {
    const { left, right, val, lazy } = tree[idx]
    if (l <= left && r >= right) return val

    const mid = Math.floor((left + right) / 2)
    if (lazy) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    let a = Infinity
    let b = Infinity
    if (l <= mid) {
        try {
        a = queryTree(tree, 2 * idx + 1, l, r)
        }catch(e) {
        throw -5
        }
    }
    if (r > mid) {
        try {
        b = queryTree(tree, 2 * idx + 2, l, r)
        }catch(e) {
        throw -6
        }
    }
    const merge = Math.min
    return merge(a, b)
}

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    // var t = parseInt(lines[0]);
    var l = 0;
    var [n, m] = lines[l++].trim().split(' ').map(Number)
    var arr = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))
    l += m
    try {
    console.log(solve(n, m, arr))
    } catch (e) {
        console.log(e)
    }
    // for (var i = 0; i < t; i++) {
    // var n = +lines[l++]
    // var a = lines[l++].trim().split(' ').map(Number)
    // var b = lines[l++].trim().split(' ').map(Number)
    // }
});

function solve(n, m, arr) {
    arr.sort((a, b) => a[2] - b[2])
// console.log(arr)
    const tree = []
    createTree(tree, 0, f(1), f(m, 1), 0)

    let i = 0
    let j = 0
    let ans = Infinity
    while (i < n) {
        let covered
        while (j < n && queryTree(tree, 0, f(1), f(m, 1)) === 0) {
    try{
            const [l, r, w] = arr[j]
            insertTree(tree, 0, f(l), f(r, 1), 1)
    }catch(e) {
        throw j + n
    }
        // console.log(tree)

            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('j++', i, j, covered)
            // if (covered) {
                // console.log(ans, i, j, arr[j][2], arr[i][2])
                // break
            // }
            j++
        }

        // if (!covered) break
        if (queryTree(tree, 0, f(1), f(m, 1)) === 0) break
    try{
        // console.log('j++', i, j - 1, covered)
                ans = Math.min(ans, arr[j - 1][2] - arr[i][2])

        // while (i <= j) {
            const [l, r, w] = arr[i]
            insertTree(tree, 0, f(l), f(r, 1), -1)

    }catch(e) {
        throw -4
    }
            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('i++', i + 1, j - 1, covered)
            // if (!covered) break

            i++
        // ans = Math.min(ans, arr[j][2] - arr[i][2])
        // }
        // if (covered) break
    }
    return ans
}
function f(x, right) {
    return right ? x - 1 : x
}

function createTree(tree, p, left, right, val) {
    tree[p] = { left, right, val, lazy: val }
    if (left === right) return

    const mid = Math.floor((left + right) / 2)
    createTree(tree, 2 * p + 1, left, mid, val)
    createTree(tree, 2 * p + 2, mid + 1, right, val)
}
function initTree(tree, merge, arr) {
    for (let i = tree.length - 1; i >= 0; i--) {
        if (!tree[i]) continue
        const { left, right } = tree[i]
        tree[i].val = left === right
            ? arr[left % arr.length]
            : merge(tree[2 * i + 1].val, tree[2 * i + 2].val)
    }
}
function insertTree(tree, idx, l, r, val) {
    const { left, right, lazy } = tree[idx]
    if (l <= left && r >= right) {
        tree[idx].val += val
        tree[idx].lazy += val
        return
    }

    if (lazy && left !== right) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    const mid = Math.floor((left + right) / 2)
    if (l <= mid) {
        try {
        insertTree(tree, 2 * idx + 1, l, r, val)
        } catch (e) {
            throw -1
        }
    }
    if (r > mid) {
        try {
            // throw 'sb'
        insertTree(tree, 2 * idx + 2, l, r, val)
        } catch (e) {
            throw -2
        }
    }
    const merge = Math.min
    tree[idx].val = merge(tree[2 * idx + 1].val, tree[2 * idx + 2].val)
}
function queryTree(tree, idx, l, r) {
    const { left, right, val, lazy } = tree[idx]
    if (l <= left && r >= right) return val

    const mid = Math.floor((left + right) / 2)
    if (lazy) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    let a = Infinity
    let b = Infinity
    if (l <= mid) {
        try {
        a = queryTree(tree, 2 * idx + 1, l, r)
        }catch(e) {
        throw -5
        }
    }
    if (r > mid) {
        try {
        b = queryTree(tree, 2 * idx + 2, l, r)
        }catch(e) {
        throw -6
        }
    }
    const merge = Math.min
    return merge(a, b)
}

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    // var t = parseInt(lines[0]);
    var l = 0;
    var [n, m] = lines[l++].trim().split(' ').map(Number)
    var arr = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))
    l += m
    try {
    console.log(solve(n, m, arr))
    } catch (e) {
        console.log(e)
    }
    // for (var i = 0; i < t; i++) {
    // var n = +lines[l++]
    // var a = lines[l++].trim().split(' ').map(Number)
    // var b = lines[l++].trim().split(' ').map(Number)
    // }
});

function solve(n, m, arr) {
    arr.sort((a, b) => a[2] - b[2])
// console.log(arr)
    const tree = []
    createTree(tree, 0, f(1), f(m, 1), 0)

    let i = 0
    let j = 0
    let ans = Infinity
    while (i < n) {
        let covered
        while (j < n && queryTree(tree, 0, f(1), f(m, 1)) === 0) {
    try{
            const [l, r, w] = arr[j]
            insertTree(tree, 0, f(l), f(r, 1), 1)
    }catch(e) {
        throw -7
    }
        // console.log(tree)

            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('j++', i, j, covered)
            // if (covered) {
                // console.log(ans, i, j, arr[j][2], arr[i][2])
                // break
            // }
            j++
        }

        // if (!covered) break
        if (queryTree(tree, 0, f(1), f(m, 1)) === 0) break
    try{
        // console.log('j++', i, j - 1, covered)
                ans = Math.min(ans, arr[j - 1][2] - arr[i][2])

        // while (i <= j) {
            const [l, r, w] = arr[i]
            insertTree(tree, 0, f(l), f(r, 1), -1)

    }catch(e) {
        throw -4
    }
            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('i++', i + 1, j - 1, covered)
            // if (!covered) break

            i++
        // ans = Math.min(ans, arr[j][2] - arr[i][2])
        // }
        // if (covered) break
    }
    return ans
}
function f(x, right) {
    return right ? x - 1 : x
}

function createTree(tree, p, left, right, val) {
    tree[p] = { left, right, val, lazy: val }
    if (left === right) return

    const mid = Math.floor((left + right) / 2)
    createTree(tree, 2 * p + 1, left, mid, val)
    createTree(tree, 2 * p + 2, mid + 1, right, val)
}
function initTree(tree, merge, arr) {
    for (let i = tree.length - 1; i >= 0; i--) {
        if (!tree[i]) continue
        const { left, right } = tree[i]
        tree[i].val = left === right
            ? arr[left % arr.length]
            : merge(tree[2 * i + 1].val, tree[2 * i + 2].val)
    }
}
function insertTree(tree, idx, l, r, val) {
    const { left, right, lazy } = tree[idx]
    if (l <= left && r >= right) {
        tree[idx].val += val
        tree[idx].lazy += val
        return
    }

    if (lazy && left !== right) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    const mid = Math.floor((left + right) / 2)
    if (l <= mid) {
        try {
        insertTree(tree, 2 * idx + 1, l, r, val)
        } catch (e) {
            throw -1
        }
    }
    if (r > mid) {
        try {
            // throw 'sb'
        insertTree(tree, 2 * idx + 2, l, r, val)
        } catch (e) {
            throw -2
        }
    }
    const merge = Math.min
    tree[idx].val = merge(tree[2 * idx + 1].val, tree[2 * idx + 2].val)
}
function queryTree(tree, idx, l, r) {
    const { left, right, val, lazy } = tree[idx]
    if (l <= left && r >= right) return val

    const mid = Math.floor((left + right) / 2)
    if (lazy) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    let a = Infinity
    let b = Infinity
    if (l <= mid) {
        try {
        a = queryTree(tree, 2 * idx + 1, l, r)
        }catch(e) {
        throw -5
        }
    }
    if (r > mid) {
        try {
        b = queryTree(tree, 2 * idx + 2, l, r)
        }catch(e) {
        throw -6
        }
    }
    const merge = Math.min
    return merge(a, b)
}

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    // var t = parseInt(lines[0]);
    var l = 0;
    var [n, m] = lines[l++].trim().split(' ').map(Number)
    var arr = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))
    l += m
    try {
    console.log(solve(n, m, arr))
    } catch (e) {
        console.log(e)
    }
    // for (var i = 0; i < t; i++) {
    // var n = +lines[l++]
    // var a = lines[l++].trim().split(' ').map(Number)
    // var b = lines[l++].trim().split(' ').map(Number)
    // }
});

function solve(n, m, arr) {
    arr.sort((a, b) => a[2] - b[2])
// console.log(arr)
    const tree = []
    createTree(tree, 0, f(1), f(m, 1), 0)

    let i = 0
    let j = 0
    let ans = Infinity
    while (i < n) {
        try{
        let covered
        while (j < n && queryTree(tree, 0, f(1), f(m, 1)) === 0) {
            const [l, r, w] = arr[j]
            insertTree(tree, 0, f(l), f(r, 1), 1)
        // console.log(tree)

            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('j++', i, j, covered)
            // if (covered) {
                // console.log(ans, i, j, arr[j][2], arr[i][2])
                // break
            // }
            j++
        }
    }catch(e) {
        throw -3
    }
        // if (!covered) break
        if (queryTree(tree, 0, f(1), f(m, 1)) === 0) break
    try{
        // console.log('j++', i, j - 1, covered)
                ans = Math.min(ans, arr[j - 1][2] - arr[i][2])

        // while (i <= j) {
            const [l, r, w] = arr[i]
            insertTree(tree, 0, f(l), f(r, 1), -1)

    }catch(e) {
        throw -4
    }
            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('i++', i + 1, j - 1, covered)
            // if (!covered) break

            i++
        // ans = Math.min(ans, arr[j][2] - arr[i][2])
        // }
        // if (covered) break
    }
    return ans
}
function f(x, right) {
    return right ? x - 1 : x
}

function createTree(tree, p, left, right, val) {
    tree[p] = { left, right, val, lazy: val }
    if (left === right) return

    const mid = Math.floor((left + right) / 2)
    createTree(tree, 2 * p + 1, left, mid, val)
    createTree(tree, 2 * p + 2, mid + 1, right, val)
}
function initTree(tree, merge, arr) {
    for (let i = tree.length - 1; i >= 0; i--) {
        if (!tree[i]) continue
        const { left, right } = tree[i]
        tree[i].val = left === right
            ? arr[left % arr.length]
            : merge(tree[2 * i + 1].val, tree[2 * i + 2].val)
    }
}
function insertTree(tree, idx, l, r, val) {
    const { left, right, lazy } = tree[idx]
    if (l <= left && r >= right) {
        tree[idx].val += val
        tree[idx].lazy += val
        return
    }

    if (lazy && left !== right) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    const mid = Math.floor((left + right) / 2)
    if (l <= mid) {
        try {
        insertTree(tree, 2 * idx + 1, l, r, val)
        } catch (e) {
            throw -1
        }
    }
    if (r > mid) {
        try {
            // throw 'sb'
        insertTree(tree, 2 * idx + 2, l, r, val)
        } catch (e) {
            throw -2
        }
    }
    const merge = Math.min
    tree[idx].val = merge(tree[2 * idx + 1].val, tree[2 * idx + 2].val)
}
function queryTree(tree, idx, l, r) {
    const { left, right, val, lazy } = tree[idx]
    if (l <= left && r >= right) return val

    const mid = Math.floor((left + right) / 2)
    if (lazy) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    let a = Infinity
    let b = Infinity
    if (l <= mid) {
        a = queryTree(tree, 2 * idx + 1, l, r)
    }
    if (r > mid) {
        b = queryTree(tree, 2 * idx + 2, l, r)
    }
    const merge = Math.min
    return merge(a, b)
}

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    // var t = parseInt(lines[0]);
    var l = 0;
    var [n, m] = lines[l++].trim().split(' ').map(Number)
    var arr = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))
    l += m
    try {
    console.log(solve(n, m, arr))
    } catch (e) {
        console.log(e)
    }
    // for (var i = 0; i < t; i++) {
    // var n = +lines[l++]
    // var a = lines[l++].trim().split(' ').map(Number)
    // var b = lines[l++].trim().split(' ').map(Number)
    // }
});

function solve(n, m, arr) {
    arr.sort((a, b) => a[2] - b[2])
// console.log(arr)
    const tree = []
    createTree(tree, 0, f(1), f(m, 1), 0)

    let i = 0
    let j = 0
    let ans = Infinity
    while (i < n) {
        let covered
        while (j < n && queryTree(tree, 0, f(1), f(m, 1)) === 0) {
            const [l, r, w] = arr[j]
            insertTree(tree, 0, f(l), f(r, 1), 1)
        // console.log(tree)

            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('j++', i, j, covered)
            // if (covered) {
                // console.log(ans, i, j, arr[j][2], arr[i][2])
                // break
            // }
            j++
        }
        // if (!covered) break
        if (queryTree(tree, 0, f(1), f(m, 1)) === 0) break
        // console.log('j++', i, j - 1, covered)
                ans = Math.min(ans, arr[j - 1][2] - arr[i][2])

        // while (i <= j) {
            const [l, r, w] = arr[i]
            insertTree(tree, 0, f(l), f(r, 1), -1)

            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('i++', i + 1, j - 1, covered)
            // if (!covered) break

            i++
        // ans = Math.min(ans, arr[j][2] - arr[i][2])
        // }
        // if (covered) break
    }
    return ans
}
function f(x, right) {
    return right ? x - 1 : x
}

function createTree(tree, p, left, right, val) {
    tree[p] = { left, right, val, lazy: val }
    if (left === right) return

    const mid = Math.floor((left + right) / 2)
    createTree(tree, 2 * p + 1, left, mid, val)
    createTree(tree, 2 * p + 2, mid + 1, right, val)
}
function initTree(tree, merge, arr) {
    for (let i = tree.length - 1; i >= 0; i--) {
        if (!tree[i]) continue
        const { left, right } = tree[i]
        tree[i].val = left === right
            ? arr[left % arr.length]
            : merge(tree[2 * i + 1].val, tree[2 * i + 2].val)
    }
}
function insertTree(tree, idx, l, r, val) {
    const { left, right, lazy } = tree[idx]
    if (l <= left && r >= right) {
        tree[idx].val += val
        tree[idx].lazy += val
        return
    }

    if (lazy && left !== right) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    const mid = Math.floor((left + right) / 2)
    if (l <= mid) {
        try {
        insertTree(tree, 2 * idx + 1, l, r, val)
        } catch (e) {
            throw -1
        }
    }
    if (r > mid) {
        try {
            // throw 'sb'
        insertTree(tree, 2 * idx + 2, l, r, val)
        } catch (e) {
            throw -2
        }
    }
    const merge = Math.min
    tree[idx].val = merge(tree[2 * idx + 1].val, tree[2 * idx + 2].val)
}
function queryTree(tree, idx, l, r) {
    const { left, right, val, lazy } = tree[idx]
    if (l <= left && r >= right) return val

    const mid = Math.floor((left + right) / 2)
    if (lazy) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    let a = Infinity
    let b = Infinity
    if (l <= mid) {
        a = queryTree(tree, 2 * idx + 1, l, r)
    }
    if (r > mid) {
        b = queryTree(tree, 2 * idx + 2, l, r)
    }
    const merge = Math.min
    return merge(a, b)
}

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    // var t = parseInt(lines[0]);
    var l = 0;
    var [n, m] = lines[l++].trim().split(' ').map(Number)
    var arr = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))
    l += m
    try {
    console.log(solve(n, m, arr))
    } catch (e) {
        console.log(e)
    }
    // for (var i = 0; i < t; i++) {
    // var n = +lines[l++]
    // var a = lines[l++].trim().split(' ').map(Number)
    // var b = lines[l++].trim().split(' ').map(Number)
    // }
});

function solve(n, m, arr) {
    arr.sort((a, b) => a[2] - b[2])
// console.log(arr)
    const tree = []
    createTree(tree, 0, f(1), f(m, 1), 0)

    let i = 0
    let j = 0
    let ans = Infinity
    while (i < n) {
        let covered
        while (j < n && queryTree(tree, 0, f(1), f(m, 1)) === 0) {
            const [l, r, w] = arr[j]
            insertTree(tree, 0, f(l), f(r, 1), 1)
        // console.log(tree)

            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('j++', i, j, covered)
            // if (covered) {
                // console.log(ans, i, j, arr[j][2], arr[i][2])
                // break
            // }
            j++
        }
        // if (!covered) break
        if (queryTree(tree, 0, f(1), f(m, 1)) === 0) break
        // console.log('j++', i, j - 1, covered)
                ans = Math.min(ans, arr[j - 1][2] - arr[i][2])

        // while (i <= j) {
            const [l, r, w] = arr[i]
            insertTree(tree, 0, f(l), f(r, 1), -1)

            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('i++', i + 1, j - 1, covered)
            // if (!covered) break

            i++
        // ans = Math.min(ans, arr[j][2] - arr[i][2])
        // }
        // if (covered) break
    }
    return ans
}
function f(x, right) {
    return right ? x - 1 : x
}

function createTree(tree, p, left, right, val) {
    tree[p] = { left, right, val, lazy: val }
    if (left === right) return

    const mid = Math.floor((left + right) / 2)
    createTree(tree, 2 * p + 1, left, mid, val)
    createTree(tree, 2 * p + 2, mid + 1, right, val)
}
function initTree(tree, merge, arr) {
    for (let i = tree.length - 1; i >= 0; i--) {
        if (!tree[i]) continue
        const { left, right } = tree[i]
        tree[i].val = left === right
            ? arr[left % arr.length]
            : merge(tree[2 * i + 1].val, tree[2 * i + 2].val)
    }
}
function insertTree(tree, idx, l, r, val) {
    const { left, right, lazy } = tree[idx]
    if (l <= left && r >= right) {
        tree[idx].val += val
        tree[idx].lazy += val
        return
    }

    if (lazy && left !== right) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    const mid = Math.floor((left + right) / 2)
    if (l <= mid) {
        try {
        insertTree(tree, 2 * idx + 1, l, r, val)
        } catch (e) {
            throw ['a', 2 * idx + 1, l, r, val].join(' ')
        }
    }
    if (r > mid) {
        try {
            // throw 'sb'
        insertTree(tree, 2 * idx + 2, l, r, val)
        } catch (e) {
            throw ['b', 2 * idx + 2, l, r, val].join(' ')
        }
    }
    const merge = Math.min
    tree[idx].val = merge(tree[2 * idx + 1].val, tree[2 * idx + 2].val)
}
function queryTree(tree, idx, l, r) {
    const { left, right, val, lazy } = tree[idx]
    if (l <= left && r >= right) return val

    const mid = Math.floor((left + right) / 2)
    if (lazy) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    let a = Infinity
    let b = Infinity
    if (l <= mid) {
        a = queryTree(tree, 2 * idx + 1, l, r)
    }
    if (r > mid) {
        b = queryTree(tree, 2 * idx + 2, l, r)
    }
    const merge = Math.min
    return merge(a, b)
}

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    // var t = parseInt(lines[0]);
    var l = 0;
    var [n, m] = lines[l++].trim().split(' ').map(Number)
    var arr = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))
    l += m
    try {
    console.log(solve(n, m, arr))
    } catch (e) {
        console.log(e.stack)
    }
    // for (var i = 0; i < t; i++) {
    // var n = +lines[l++]
    // var a = lines[l++].trim().split(' ').map(Number)
    // var b = lines[l++].trim().split(' ').map(Number)
    // }
});

function solve(n, m, arr) {
    arr.sort((a, b) => a[2] - b[2])
// console.log(arr)
    const tree = []
    createTree(tree, 0, f(1), f(m, 1), 0)

    let i = 0
    let j = 0
    let ans = Infinity
    while (i < n) {
        let covered
        while (j < n && queryTree(tree, 0, f(1), f(m, 1)) === 0) {
            const [l, r, w] = arr[j]
            insertTree(tree, 0, f(l), f(r, 1), 1)
        // console.log(tree)

            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('j++', i, j, covered)
            // if (covered) {
                // console.log(ans, i, j, arr[j][2], arr[i][2])
                // break
            // }
            j++
        }
        // if (!covered) break
        if (queryTree(tree, 0, f(1), f(m, 1)) === 0) break
        // console.log('j++', i, j - 1, covered)
                ans = Math.min(ans, arr[j - 1][2] - arr[i][2])

        // while (i <= j) {
            const [l, r, w] = arr[i]
            insertTree(tree, 0, f(l), f(r, 1), -1)

            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('i++', i + 1, j - 1, covered)
            // if (!covered) break

            i++
        // ans = Math.min(ans, arr[j][2] - arr[i][2])
        // }
        // if (covered) break
    }
    return ans
}
function f(x, right) {
    return right ? x - 1 : x
}

function createTree(tree, p, left, right, val) {
    tree[p] = { left, right, val, lazy: val }
    if (left === right) return

    const mid = Math.floor((left + right) / 2)
    createTree(tree, 2 * p + 1, left, mid, val)
    createTree(tree, 2 * p + 2, mid + 1, right, val)
}
function initTree(tree, merge, arr) {
    for (let i = tree.length - 1; i >= 0; i--) {
        if (!tree[i]) continue
        const { left, right } = tree[i]
        tree[i].val = left === right
            ? arr[left % arr.length]
            : merge(tree[2 * i + 1].val, tree[2 * i + 2].val)
    }
}
function insertTree(tree, idx, l, r, val) {
    const { left, right, lazy } = tree[idx]
    if (l <= left && r >= right) {
        tree[idx].val += val
        tree[idx].lazy += val
        return
    }

    if (lazy && left !== right) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    const mid = Math.floor((left + right) / 2)
    if (l <= mid) {
        insertTree(tree, 2 * idx + 1, l, r, val)
    }
    if (r > mid) {
        insertTree(tree, 2 * idx + 2, l, r, val)
    }
    const merge = Math.min
    tree[idx].val = merge(tree[2 * idx + 1].val, tree[2 * idx + 2].val)
}
function queryTree(tree, idx, l, r) {
    const { left, right, val, lazy } = tree[idx]
    if (l <= left && r >= right) return val

    const mid = Math.floor((left + right) / 2)
    if (lazy) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    let a = Infinity
    let b = Infinity
    if (l <= mid) {
        a = queryTree(tree, 2 * idx + 1, l, r)
    }
    if (r > mid) {
        b = queryTree(tree, 2 * idx + 2, l, r)
    }
    const merge = Math.min
    return merge(a, b)
}

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    // var t = parseInt(lines[0]);
    var l = 0;
    var [n, m] = lines[l++].trim().split(' ').map(Number)
    var arr = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))
    l += m
    console.log(solve(n, m, arr))
    // for (var i = 0; i < t; i++) {
    // var n = +lines[l++]
    // var a = lines[l++].trim().split(' ').map(Number)
    // var b = lines[l++].trim().split(' ').map(Number)
    // }
});

function solve(n, m, arr) {
    arr.sort((a, b) => a[2] - b[2])
// console.log(arr)
    const tree = []
    createTree(tree, 0, f(1), f(m, 1), 0)

    let i = 0
    let j = 0
    let ans = Infinity
    while (i < n && j < n) {
        let covered
        while (j < n && queryTree(tree, 0, f(1), f(m, 1)) === 0) {
            const [l, r, w] = arr[j]
            insertTree(tree, 0, f(l), f(r, 1), 1)
        // console.log(tree)

            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('j++', i, j, covered)
            // if (covered) {
                // console.log(ans, i, j, arr[j][2], arr[i][2])
                // break
            // }
            j++
        }
        // if (!covered) break
        if (queryTree(tree, 0, f(1), f(m, 1)) === 0) break
                ans = Math.min(ans, arr[j - 1][2] - arr[i][2])

        // while (i <= j) {
            const [l, r, w] = arr[i]
            insertTree(tree, 0, f(l), f(r, 1), -1)

            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('i++', i + 1, j, covered)
            // if (!covered) break

            i++
        // ans = Math.min(ans, arr[j][2] - arr[i][2])
        // }
        // if (covered) break
    }
    return ans
}
function f(x, right) {
    return right ? x - 1 : x
}

function createTree(tree, p, left, right, val) {
    tree[p] = { left, right, val, lazy: val }
    if (left === right) return

    const mid = Math.floor((left + right) / 2)
    createTree(tree, 2 * p + 1, left, mid, val)
    createTree(tree, 2 * p + 2, mid + 1, right, val)
}
function initTree(tree, merge, arr) {
    for (let i = tree.length - 1; i >= 0; i--) {
        if (!tree[i]) continue
        const { left, right } = tree[i]
        tree[i].val = left === right
            ? arr[left % arr.length]
            : merge(tree[2 * i + 1].val, tree[2 * i + 2].val)
    }
}
function insertTree(tree, idx, l, r, val) {
    const { left, right, lazy } = tree[idx]
    if (l <= left && r >= right) {
        tree[idx].val += val
        tree[idx].lazy += val
        return
    }

    if (lazy && left !== right) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    const mid = Math.floor((left + right) / 2)
    if (l <= mid) {
        insertTree(tree, 2 * idx + 1, l, r, val)
    }
    if (r > mid) {
        insertTree(tree, 2 * idx + 2, l, r, val)
    }
    const merge = Math.min
    tree[idx].val = merge(tree[2 * idx + 1].val, tree[2 * idx + 2].val)
}
function queryTree(tree, idx, l, r) {
    const { left, right, val, lazy } = tree[idx]
    if (l <= left && r >= right) return val

    const mid = Math.floor((left + right) / 2)
    if (lazy) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    let a = Infinity
    let b = Infinity
    if (l <= mid) {
        a = queryTree(tree, 2 * idx + 1, l, r)
    }
    if (r > mid) {
        b = queryTree(tree, 2 * idx + 2, l, r)
    }
    const merge = Math.min
    return merge(a, b)
}

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    // var t = parseInt(lines[0]);
    var l = 0;
    var [n, m] = lines[l++].trim().split(' ').map(Number)
    var arr = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))
    l += m
    console.log(solve(n, m, arr))
    // for (var i = 0; i < t; i++) {
    // var n = +lines[l++]
    // var a = lines[l++].trim().split(' ').map(Number)
    // var b = lines[l++].trim().split(' ').map(Number)
    // }
});

function solve(n, m, arr) {
    arr.sort((a, b) => a[2] - b[2])
// console.log(arr)
    const tree = []
    createTree(tree, 0, f(1), f(m, 1), 0)

    let i = 0
    let j = 0
    let ans = Infinity
    while (i < n && j < n) {
        let covered
        while (j < n) {
            const [l, r, w] = arr[j]
            insertTree(tree, 0, f(l), f(r, 1), 1)
        // console.log(tree)

            covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('j++', i, j, covered)
            if (covered) {
                ans = Math.min(ans, arr[j][2] - arr[i][2])
                // console.log(ans, i, j, arr[j][2], arr[i][2])
            j++
                break
            }
            j++
        }
        if (!covered) break

        // while (i <= j) {
            const [l, r, w] = arr[i]
            insertTree(tree, 0, f(l), f(r, 1), -1)

            // covered = queryTree(tree, 0, f(1), f(m, 1)) > 0
        // console.log('i++', i + 1, j, covered)
            // if (!covered) break

            i++
        // ans = Math.min(ans, arr[j][2] - arr[i][2])
        // }
        // if (covered) break
    }
    return ans
}
function f(x, right) {
    return right ? x - 1 : x
}

function createTree(tree, p, left, right, val) {
    tree[p] = { left, right, val, lazy: val }
    if (left === right) return

    const mid = Math.floor((left + right) / 2)
    createTree(tree, 2 * p + 1, left, mid, val)
    createTree(tree, 2 * p + 2, mid + 1, right, val)
}
function initTree(tree, merge, arr) {
    for (let i = tree.length - 1; i >= 0; i--) {
        if (!tree[i]) continue
        const { left, right } = tree[i]
        tree[i].val = left === right
            ? arr[left % arr.length]
            : merge(tree[2 * i + 1].val, tree[2 * i + 2].val)
    }
}
function insertTree(tree, idx, l, r, val) {
    const { left, right, lazy } = tree[idx]
    if (l <= left && r >= right) {
        tree[idx].val += val
        tree[idx].lazy += val
        return
    }

    if (lazy && left !== right) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    const mid = Math.floor((left + right) / 2)
    if (l <= mid) {
        insertTree(tree, 2 * idx + 1, l, r, val)
    }
    if (r > mid) {
        insertTree(tree, 2 * idx + 2, l, r, val)
    }
    const merge = Math.min
    tree[idx].val = merge(tree[2 * idx + 1].val, tree[2 * idx + 2].val)
}
function queryTree(tree, idx, l, r) {
    const { left, right, val, lazy } = tree[idx]
    if (l <= left && r >= right) return val

    const mid = Math.floor((left + right) / 2)
    if (lazy) {
        tree[2 * idx + 1].val += lazy
        tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy += lazy
        tree[2 * idx + 2].lazy += lazy
        tree[idx].lazy = 0
    }

    let a = Infinity
    let b = Infinity
    if (l <= mid) {
        a = queryTree(tree, 2 * idx + 1, l, r)
    }
    if (r > mid) {
        b = queryTree(tree, 2 * idx + 2, l, r)
    }
    const merge = Math.min
    return merge(a, b)
}

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    // var t = parseInt(lines[0]);
    var l = 0;
    var [n, m] = lines[l++].trim().split(' ').map(Number)
    var arr = lines.slice(l, l + m).map(str => str.trim().split(' ').map(Number))
    l += m
    console.log(solve(n, m, arr))
    // for (var i = 0; i < t; i++) {
    //     var n = +lines[l++]
    //     var a = lines[l++].trim().split(' ').map(Number)
    //     var b = lines[l++].trim().split(' ').map(Number)
    // }
});

function solve(n, m, arr) {
    arr.sort((a, b) => a[2] - b[2])
// console.log(arr)
    const tree = []
    createTree(tree, 0, f(1), f(m), 0)

    let i = 0
    let j = 0
    let ans = Infinity
    while (i < n && j < n) {
        let covered
        while (j < n) {
            const [l, r, w] = arr[j]
            insertTree(tree, 0, f(l), f(r), 1)
            // console.log(tree)

            covered = queryTree(tree, 0, f(1), f(m), and)
        // console.log('j++', i, j, covered)
            if (covered) {
                ans = Math.min(ans, arr[j][2] - arr[i][2])
                break
            }

            j++
        }
        if (!covered) break

        // while (i <= j) {
            const [l, r, w] = arr[i]
            insertTree(tree, 0, f(l), f(r), -1)

            covered = queryTree(tree, 0, f(1), f(m), and)
        // console.log('i++', i + 1, j, covered)
            // if (!covered) break

            i++
            // ans = Math.min(ans, arr[j][2] - arr[i][2])
        // }
        // if (covered) break
    }
    return ans
}
function f(x) {
    return 2 * x - 1
}
function and(a, b) {
    return a & b
}

function createTree(tree, p, left, right, val) {
    tree[p] = { left, right, val }
    if (left === right) return

    const mid = Math.floor((left + right) / 2)
    createTree(tree, 2 * p + 1, left, mid, val)
    createTree(tree, 2 * p + 2, mid + 1, right, val)
}
function initTree(tree, merge, arr) {
    for (let i = tree.length - 1; i >= 0; i--) {
        if (!tree[i]) continue
        const { left, right } = tree[i]
        tree[i].val = left === right
            ? arr[left % arr.length]
            : merge(tree[2 * i + 1].val, tree[2 * i + 2].val)
    }
}
function insertTree(tree, idx, l, r, val) {
    const { left, right, lazy } = tree[idx]
    if (l === left && r === right) {
        tree[idx].val += val
        tree[idx].lazy = true
        return
    }

    const mid = Math.floor((left + right) / 2)
    if (r <= mid) {
        insertTree(tree, 2 * idx + 1, l, r, val)
    } else if (l > mid) {
        insertTree(tree, 2 * idx + 2, l, r, val)
    } else {
        insertTree(tree, 2 * idx + 1, l, mid, val)
        insertTree(tree, 2 * idx + 2, mid + 1, r, val)
    }
}
function queryTree(tree, idx, l, r, merge) {
    const { left, right, lazy } = tree[idx]
    if (l === left && r === right && lazy && tree[idx].val) return tree[idx].val // lazy lag
    if (left === right) return tree[idx].val

    const mid = Math.floor((left + right) / 2)
    if (r <= mid) {
        return queryTree(tree, 2 * idx + 1, l, r, merge)
    } else if (l > mid) {
        return queryTree(tree, 2 * idx + 2, l, r, merge)
    } else {
        const a = queryTree(tree, 2 * idx + 1, l, mid, merge)
        const b = queryTree(tree, 2 * idx + 2, mid + 1, r, merge)
        return merge(a, b)
    }
}